{"id": "007d4c4f043dded0", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/src/unit-comparison.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 30961, "sha256": "7dd8b86a3bf7a436bb04bf5ddf0188e11b8542a5437965669a7ad1c20844ade6", "text": "// __ _____ _____ _____\n// __| | __| | | | JSON for Modern C++ (supporting code)\n// | | |__ | | | | | | version 3.12.0\n// |_____|_____|_____|_|___| https://github.com/nlohmann/json\n//\n// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann \n// SPDX-License-Identifier: MIT\n\n// cmake/test.cmake selects the C++ standard versions with which to build a\n// unit test based on the presence of JSON_HAS_CPP_ macros.\n// When using macros that are only defined for particular versions of the standard\n// (e.g., JSON_HAS_FILESYSTEM for C++17 and up), please mention the corresponding\n// version macro in a comment close by, like this:\n// JSON_HAS_CPP_ (do not remove; see note at top of file)\n\n#include \"doctest_compatibility.h\"\n\n#define JSON_TESTS_PRIVATE\n#include \nusing nlohmann::json;\n\n#if JSON_HAS_THREE_WAY_COMPARISON\n// this can be replaced with the doctest stl extension header in version 2.5\nnamespace doctest\n{\ntemplate<> struct StringMaker\n{\n static String convert(const std::partial_ordering& order)\n {\n if (order == std::partial_ordering::less)\n {\n return \"std::partial_ordering::less\";\n }\n if (order == std::partial_ordering::equivalent)\n {\n return \"std::partial_ordering::equivalent\";\n }\n if (order == std::partial_ordering::greater)\n {\n return \"std::partial_ordering::greater\";\n }\n if (order == std::partial_ordering::unordered)\n {\n return \"std::partial_ordering::unordered\";\n }\n return \"{?}\";\n }\n};\n} // namespace doctest\n\n#endif\n\nnamespace\n{\n// helper function to check std::less\n// see https://en.cppreference.com/w/cpp/utility/functional/less\ntemplate >\nbool f(A a, B b, U u = U())\n{\n return u(a, b);\n}\n} // namespace\n\nTEST_CASE(\"lexicographical comparison operators\")\n{\n constexpr auto f_ = false;\n constexpr auto _t = true;\n constexpr auto nan = std::numeric_limits::quiet_NaN();\n#if JSON_HAS_THREE_WAY_COMPARISON\n constexpr auto lt = std::partial_ordering::less;\n constexpr auto gt = std::partial_ordering::greater;\n constexpr auto eq = std::partial_ordering::equivalent;\n constexpr auto un = std::partial_ordering::unordered;\n#endif\n\n#if JSON_HAS_THREE_WAY_COMPARISON\n INFO(\"using 3-way comparison\");\n#endif\n\n#if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON\n INFO(\"using legacy comparison\");\n#endif\n\n //REQUIRE(std::numeric_limits::has_quiet_NaN);\n REQUIRE(std::isnan(nan));\n\n SECTION(\"types\")\n {\n std::vector j_types =\n {\n json::value_t::null,\n json::value_t::boolean,\n json::value_t::number_integer,\n json::value_t::number_unsigned,\n json::value_t::number_float,\n json::value_t::object,\n json::value_t::array,\n json::value_t::string,\n json::value_t::binary,\n json::value_t::discarded\n };\n\n std::vector> expected_lt =\n {\n //0 1 2 3 4 5 6 7 8 9\n {f_, _t, _t, _t, _t, _t, _t, _t, _t, f_}, // 0\n {f_, f_, _t, _t, _t, _t, _t, _t, _t, f_}, // 1\n {f_, f_, f_, f_, f_, _t, _t, _t, _t, f_}, // 2\n {f_, f_, f_, f_, f_, _t, _t, _t, _t, f_}, // 3\n {f_, f_, f_, f_, f_, _t, _t, _t, _t, f_}, // 4\n {f_, f_, f_, f_, f_, f_, _t, _t, _t, f_}, // 5\n {f_, f_, f_, f_, f_, f_, f_, _t, _t, f_}, // 6\n {f_, f_, f_, f_, f_, f_, f_, f_, _t, f_}, // 7\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 8\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 9\n };\n\n SECTION(\"comparison: less\")\n {\n REQUIRE(expected_lt.size() == j_types.size());\n for (size_t i = 0; i < j_types.size(); ++i)\n {\n REQUIRE(expected_lt[i].size() == j_types.size());\n for (size_t j = 0; j < j_types.size(); ++j)\n {\n CAPTURE(i)\n CAPTURE(j)\n // check precomputed values\n#if JSON_HAS_THREE_WAY_COMPARISON\n // JSON_HAS_CPP_20 (do not remove; see note at top of file)\n CHECK((j_types[i] < j_types[j]) == expected_lt[i][j]);\n#else\n CHECK(operator<(j_types[i], j_types[j]) == expected_lt[i][j]);\n#endif\n CHECK(f(j_types[i], j_types[j]) == expected_lt[i][j]);\n }\n }\n }\n#if JSON_HAS_THREE_WAY_COMPARISON\n // JSON_HAS_CPP_20 (do not remove; see note at top of file)\n SECTION(\"comparison: 3-way\")\n {\n std::vector> expected =\n {\n //0 1 2 3 4 5 6 7 8 9\n {eq, lt, lt, lt, lt, lt, lt, lt, lt, un}, // 0\n {gt, eq, lt, lt, lt, lt, lt, lt, lt, un}, // 1\n {gt, gt, eq, eq, eq, lt, lt, lt, lt, un}, // 2\n {gt, gt, eq, eq, eq, lt, lt, lt, lt, un}, // 3\n {gt, gt, eq, eq, eq, lt, lt, lt, lt, un}, // 4\n {gt, gt, gt, gt, gt, eq, lt, lt, lt, un}, // 5\n {gt, gt, gt, gt, gt, gt, eq, lt, lt, un}, // 6\n {gt, gt, gt, gt, gt, gt, gt, eq, lt, un}, // 7\n {gt, gt, gt, gt, gt, gt, gt, gt, eq, un}, // 8\n {un, un, un, un, un, un, un, un, un, un}, // 9\n };\n\n // check expected partial_ordering against expected boolean\n REQUIRE(expected.size() == expected_lt.size());\n for (size_t i = 0; i < expected.size(); ++i)\n {\n REQUIRE(expected[i].size() == expected_lt[i].size());\n for (size_t j = 0; j < expected[i].size(); ++j)\n {\n CAPTURE(i)\n CAPTURE(j)\n CHECK(std::is_lt(expected[i][j]) == expected_lt[i][j]);\n }\n }\n\n // check 3-way comparison against expected partial_ordering\n REQUIRE(expected.size() == j_types.size());\n for (size_t i = 0; i < j_types.size(); ++i)\n {\n REQUIRE(expected[i].size() == j_types.size());\n for (size_t j = 0; j < j_types.size(); ++j)\n {\n CAPTURE(i)\n CAPTURE(j)\n CHECK((j_types[i] <=> j_types[j]) == expected[i][j]); // *NOPAD*\n }\n }\n }\n#endif\n }\n\n SECTION(\"values\")\n {\n json j_values =\n {\n nullptr, nullptr, // 0 1\n -17, 42, // 2 3\n 8u, 13u, // 4 5\n 3.14159, 23.42, // 6 7\n nan, nan, // 8 9\n \"foo\", \"bar\", // 10 11\n true, false, // 12 13\n {1, 2, 3}, {\"one\", \"two\", \"three\"}, // 14 15\n {{\"first\", 1}, {\"second\", 2}}, {{\"a\", \"A\"}, {\"b\", {\"B\"}}}, // 16 17\n json::binary({1, 2, 3}), json::binary({1, 2, 4}), // 18 19\n json(json::value_t::discarded), json(json::value_t::discarded) // 20 21\n };\n\n std::vector> expected_eq =\n {\n //0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21\n {_t, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 0\n {_t, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 1\n {f_, f_, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 2\n {f_, f_, f_, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 3\n {f_, f_, f_, f_, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 4\n {f_, f_, f_, f_, f_, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 5\n {f_, f_, f_, f_, f_, f_, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 6\n {f_, f_, f_, f_, f_, f_, f_, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 7\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 8\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 9\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 10\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 11\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 12\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, f_, f_, f_, f_, f_, f_, f_, f_}, // 13\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, f_, f_, f_, f_, f_, f_, f_}, // 14\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, f_, f_, f_, f_, f_, f_}, // 15\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, f_, f_, f_, f_, f_}, // 16\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, f_, f_, f_, f_}, // 17\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, f_, f_, f_}, // 18\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, f_, f_}, // 19\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 20\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 21\n };\n\n std::vector> expected_lt =\n {\n //0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21\n {f_, f_, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, f_, f_}, // 0\n {f_, f_, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, f_, f_}, // 1\n {f_, f_, f_, _t, _t, _t, _t, _t, f_, f_, _t, _t, f_, f_, _t, _t, _t, _t, _t, _t, f_, f_}, // 2\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_, _t, _t, _t, _t, _t, _t, f_, f_}, // 3\n {f_, f_, f_, _t, f_, _t, f_, _t, f_, f_, _t, _t, f_, f_, _t, _t, _t, _t, _t, _t, f_, f_}, // 4\n {f_, f_, f_, _t, f_, f_, f_, _t, f_, f_, _t, _t, f_, f_, _t, _t, _t, _t, _t, _t, f_, f_}, // 5\n {f_, f_, f_, _t, _t, _t, f_, _t, f_, f_, _t, _t, f_, f_, _t, _t, _t, _t, _t, _t, f_, f_}, // 6\n {f_, f_, f_, _t, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_, _t, _t, _t, _t, _t, _t, f_, f_}, // 7\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_, _t, _t, _t, _t, _t, _t, f_, f_}, // 8\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_, _t, _t, _t, _t, _t, _t, f_, f_}, // 9\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_}, // 10\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, f_, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_}, // 11\n {f_, f_, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, f_, f_, _t, _t, _t, _t, _t, _t, f_, f_}, // 12\n {f_, f_, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, f_, _t, _t, _t, _t, _t, _t, f_, f_}, // 13\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_, f_, _t, f_, f_, _t, _t, f_, f_}, // 14\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_}, // 15\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_, _t, _t, f_, f_, _t, _t, f_, f_}, // 16\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_, _t, _t, _t, f_, _t, _t, f_, f_}, // 17\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, f_, f_}, // 18\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 19\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 20\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 21\n };\n\n SECTION(\"compares unordered\")\n {\n std::vector> expected =\n {\n //0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t}, // 0\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t}, // 1\n {f_, f_, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t}, // 2\n {f_, f_, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t}, // 3\n {f_, f_, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t}, // 4\n {f_, f_, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t}, // 5\n {f_, f_, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t}, // 6\n {f_, f_, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t}, // 7\n {f_, f_, _t, _t, _t, _t, _t, _t, _t, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t}, // 8\n {f_, f_, _t, _t, _t, _t, _t, _t, _t, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t}, // 9\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t}, // 10\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t}, // 11\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t}, // 12\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t}, // 13\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t}, // 14\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t}, // 15\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t}, // 16\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t}, // 17\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t}, // 18\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, _t, _t}, // 19\n {_t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t}, // 20\n {_t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t, _t}, // 21\n };\n\n // check if two values compare unordered as expected\n REQUIRE(expected.size() == j_values.size());\n for (size_t i = 0; i < j_values.size(); ++i)\n {\n REQUIRE(expected[i].size() == j_values.size());\n for (size_t j = 0; j < j_values.size(); ++j)\n {\n CAPTURE(i)\n CAPTURE(j)\n CHECK(json::compares_unordered(j_values[i], j_values[j]) == expected[i][j]);\n }\n }\n }\n\n#if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON\n SECTION(\"compares unordered (inverse)\")\n {\n std::vector> expected =\n {\n //0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 0\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 1\n {f_, f_, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 2\n {f_, f_, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 3\n {f_, f_, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 4\n {f_, f_, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 5\n {f_, f_, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 6\n {f_, f_, f_, f_, f_, f_, f_, f_, _t, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 7\n {f_, f_, _t, _t, _t, _t, _t, _t, _t, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 8\n {f_, f_, _t, _t, _t, _t, _t, _t, _t, _t, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 9\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 10\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 11\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 12\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 13\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 14\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 15\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 16\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 17\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 18\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 19\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 20\n {f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_, f_}, // 21\n };\n\n // check that two values compare unordered as expected (with legacy-mode enabled)\n REQUIRE(expected.size() == j_values.size());\n for (size_t i = 0; i < j_values.size(); ++i)\n {\n REQUIRE(expected[i].size() == j_values.size());\n for (size_t j = 0; j < j_values.size(); ++j)\n {\n CAPTURE(i)\n CAPTURE(j)\n CAPTURE(j_values[i])\n CAPTURE(j_values[j])\n CHECK(json::compares_unordered(j_values[i], j_values[j], true) == expected[i][j]);\n }\n }\n }\n#endif\n\n SECTION(\"comparison: equal\")\n {\n // check that two values compare equal\n REQUIRE(expected_eq.size() == j_values.size());\n for (size_t i = 0; i < j_values.size(); ++i)\n {\n REQUIRE(expected_eq[i].size() == j_values.size());\n for (size_t j = 0; j < j_values.size(); ++j)\n {\n CAPTURE(i)\n CAPTURE(j)\n CHECK((j_values[i] == j_values[j]) == expected_eq[i][j]);\n }\n }\n\n // compare with null pointer\n json j_null;\n CHECK(j_null == nullptr);\n CHECK(nullptr == j_null);\n }\n\n SECTION(\"comparison: not equal\")\n {\n // check that two values compare unequal as expected\n // operator!= now means exactly !(a==b) without special cases for NaN/discarded\n for (size_t i = 0; i < j_values.size(); ++i)\n {\n for (size_t j = 0; j < j_values.size(); ++j)\n {\n CAPTURE(i)\n CAPTURE(j)\n\n CHECK((j_values[i] != j_values[j]) == !(j_values[i] == j_values[j]));\n }\n }\n\n // compare with null pointer\n const json j_null;\n CHECK((j_null != nullptr) == !(j_null == nullptr));\n CHECK((nullptr != j_null) == !(nullptr == j_null));\n }\n\n SECTION(\"comparison: less\")\n {\n // check that two values compare less than as expected\n REQUIRE(expected_lt.size() == j_values.size());\n for (size_t i = 0; i < j_values.size(); ++i)\n {\n REQUIRE(expected_lt[i].size() == j_values.size());\n for (size_t j = 0; j < j_values.size(); ++j)\n {\n CAPTURE(i)\n CAPTURE(j)\n CHECK((j_values[i] < j_values[j]) == expected_lt[i][j]);\n }\n }\n }\n\n SECTION(\"comparison: less than or equal equal\")\n {\n // check that two values compare less than or equal as expected\n for (size_t i = 0; i < j_values.size(); ++i)\n {\n for (size_t j = 0; j < j_values.size(); ++j)\n {\n CAPTURE(i)\n CAPTURE(j)\n if (json::compares_unordered(j_values[i], j_values[j], true))\n {\n // if two values compare unordered,\n // check that the boolean comparison result is always false\n CHECK_FALSE(j_values[i] <= j_values[j]);\n }\n else\n {\n // otherwise, check that they compare according to their definition\n // as the inverse of less than with the operand order reversed\n CHECK((j_values[i] <= j_values[j]) == !(j_values[j] < j_values[i]));\n }\n }\n }\n }\n\n SECTION(\"comparison: greater than\")\n {\n // check that two values compare greater than as expected\n for (size_t i = 0; i < j_values.size(); ++i)\n {\n for (size_t j = 0; j < j_values.size(); ++j)\n {\n CAPTURE(i)\n CAPTURE(j)\n if (json::compares_unordered(j_values[i], j_values[j]))\n {\n // if two values compare unordered,\n // check that the boolean comparison result is always false\n CHECK_FALSE(j_values[i] > j_values[j]);\n }\n else\n {\n // otherwise, check that they compare according to their definition\n // as the inverse of less than or equal which is defined as\n // the inverse of less than with the operand order reversed\n CHECK((j_values[i] > j_values[j]) == !(j_values[i] <= j_values[j]));\n CHECK((j_values[i] > j_values[j]) == !!(j_values[j] < j_values[i]));\n }\n }\n }\n }\n\n SECTION(\"comparison: greater than or equal\")\n {\n // check that two values compare greater than or equal as expected\n for (size_t i = 0; i < j_values.size(); ++i)\n {\n for (size_t j = 0; j < j_values.size(); ++j)\n {\n CAPTURE(i)\n CAPTURE(j)\n if (json::compares_unordered(j_values[i], j_values[j], true))\n {\n // if two values compare unordered,\n // check that the boolean result is always false\n CHECK_FALSE(j_values[i] >= j_values[j]);\n }\n else\n {\n // otherwise, check that they compare according to their definition\n // as the inverse of less than\n CHECK((j_values[i] >= j_values[j]) == !(j_values[i] < j_values[j]));\n }\n }\n }\n }\n\n#if JSON_HAS_THREE_WAY_COMPARISON\n // JSON_HAS_CPP_20 (do not remove; see note at top of file)\n SECTION(\"comparison: 3-way\")\n {\n std::vector> expected =\n {\n //0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21\n {eq, eq, lt, lt, lt, lt, lt, lt, lt, lt, lt, lt, lt, lt, lt, lt, lt, lt, lt, lt, un, un}, // 0\n {eq, eq, lt, lt, lt, lt, lt, lt, lt, lt, lt, lt, lt, lt, lt, lt, lt, lt, lt, lt, un, un}, // 1\n {gt, gt, eq, lt, lt, lt, lt, lt, un, un, lt, lt, gt, gt, lt, lt, lt, lt, lt, lt, un, un}, // 2\n {gt, gt, gt, eq, gt, gt, gt, gt, un, un, lt, lt, gt, gt, lt, lt, lt, lt, lt, lt, un, un}, // 3\n {gt, gt, gt, lt, eq, lt, gt, lt, un, un, lt, lt, gt, gt, lt, lt, lt, lt, lt, lt, un, un}, // 4\n {gt, gt, gt, lt, gt, eq, gt, lt, un, un, lt, lt, gt, gt, lt, lt, lt, lt, lt, lt, un, un}, // 5\n {gt, gt, gt, lt, lt, lt, eq, lt, un, un, lt, lt, gt, gt, lt, lt, lt, lt, lt, lt, un, un}, // 6\n {gt, gt, gt, lt, gt, gt, gt, eq, un, un, lt, lt, gt, gt, lt, lt, lt, lt, lt, lt, un, un}, // 7\n {gt, gt, un, un, un, un, un, un, un, un, lt, lt, gt, gt, lt, lt, lt, lt, lt, lt, un, un}, // 8\n {gt, gt, un, un, un, un, un, un, un, un, lt, lt, gt, gt, lt, lt, lt, lt, lt, lt, un, un}, // 9\n {gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, eq, gt, gt, gt, gt, gt, gt, gt, lt, lt, un, un}, // 10\n {gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, lt, eq, gt, gt, gt, gt, gt, gt, lt, lt, un, un}, // 11\n {gt, gt, lt, lt, lt, lt, lt, lt, lt, lt, lt, lt, eq, gt, lt, lt, lt, lt, lt, lt, un, un}, // 12\n {gt, gt, lt, lt, lt, lt, lt, lt, lt, lt, lt, lt, lt, eq, lt, lt, lt, lt, lt, lt, un, un}, // 13\n {gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, lt, lt, gt, gt, eq, lt, gt, gt, lt, lt, un, un}, // 14\n {gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, lt, lt, gt, gt, gt, eq, gt, gt, lt, lt, un, un}, // 15\n {gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, lt, lt, gt, gt, lt, lt, eq, gt, lt, lt, un, un}, // 16\n {gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, lt, lt, gt, gt, lt, lt, lt, eq, lt, lt, un, un}, // 17\n {gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, eq, lt, un, un}, // 18\n {gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, gt, eq, un, un}, // 19\n {un, un, un, un, un, un, un, un, un, un, un, un, un, un, un, un, un, un, un, un, un, un}, // 20\n {un, un, un, un, un, un, un, un, un, un, un, un, un, un, un, un, un, un, un, un, un, un}, // 21\n };\n\n // check expected partial_ordering against expected booleans\n REQUIRE(expected.size() == expected_eq.size());\n REQUIRE(expected.size() == expected_lt.size());\n for (size_t i = 0; i < expected.size(); ++i)\n {\n REQUIRE(expected[i].size() == expected_eq[i].size());\n REQUIRE(expected[i].size() == expected_lt[i].size());\n for (size_t j = 0; j < expected[i].size(); ++j)\n {\n CAPTURE(i)\n CAPTURE(j)\n CHECK(std::is_eq(expected[i][j]) == expected_eq[i][j]);\n CHECK(std::is_lt(expected[i][j]) == expected_lt[i][j]);\n if (std::is_gt(expected[i][j]))\n {\n CHECK((!expected_eq[i][j] && !expected_lt[i][j]));\n }\n }\n }\n\n // check that two values compare according to their expected ordering\n REQUIRE(expected.size() == j_values.size());\n for (size_t i = 0; i < j_values.size(); ++i)\n {\n REQUIRE(expected[i].size() == j_values.size());\n for (size_t j = 0; j < j_values.size(); ++j)\n {\n CAPTURE(i)\n CAPTURE(j)\n CHECK((j_values[i] <=> j_values[j]) == expected[i][j]); // *NOPAD*\n }\n }\n }\n#endif\n }\n\n#if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON\n SECTION(\"parser callback regression\")\n {\n SECTION(\"filter specific element\")\n {\n const auto* s_object = R\"(\n {\n \"foo\": 2,\n \"bar\": {\n \"baz\": 1\n }\n }\n )\";\n const auto* s_array = R\"(\n [1,2,[3,4,5],4,5]\n )\";\n\n const json j_object = json::parse(s_object, [](int /*unused*/, json::parse_event_t /*unused*/, const json & j) noexcept\n {\n // filter all number(2) elements\n return j != json(2);\n });\n\n CHECK (j_object == json({{\"bar\", {{\"baz\", 1}}}}));\n\n const json j_array = json::parse(s_array, [](int /*unused*/, json::parse_event_t /*unused*/, const json & j) noexcept\n {\n return j != json(2);\n });\n\n CHECK (j_array == json({1, {3, 4, 5}, 4, 5}));\n }\n }\n#endif\n}\n\n#if JSON_HAS_THREE_WAY_COMPARISON\n// JSON_HAS_CPP_20 (do not remove; see note at top of file)\n\nTEST_CASE(\"regression #3868 - heterogeneous comparisons compile under C++20 (P2468R2)\")\n{\n // Issue #3868: operator!= was preventing compiler from synthesizing reversed\n // operator== candidates under C++20's P2468R2 rewritten candidate rules.\n // Verify that heterogeneous comparisons now work.\n\n SECTION(\"string vs json\")\n {\n std::string s = \"string\";\n json j = \"string\";\n CHECK(s == j);\n CHECK(j == s);\n CHECK_FALSE(s != j);\n CHECK_FALSE(j != s);\n }\n\n SECTION(\"other heterogeneous types\")\n {\n int i = 42;\n json j = 42;\n CHECK(i == j);\n CHECK(j == i);\n CHECK_FALSE(i != j);\n CHECK_FALSE(j != i);\n }\n}\n#endif", "messages": null, "tools": null} {"id": "008f899405e61aa2", "category": "code", "domain": "code", "source": "fmt", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "test/assert-test.cc", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/fmtlib/fmt", "commit": "4f645a8d5d7aa6f8c5ba57e9af0396e4761d3f81", "collector": "tools/harvest.py"}, "chars": 874, "sha256": "641e8d3bd0d9d118be355940b198a3f7f91e3f909d91e25c88da70397c82b79b", "text": "// Formatting library for C++ - FMT_ASSERT test\n//\n// It is a separate test to minimize the number of EXPECT_DEBUG_DEATH checks\n// which are slow on some platforms. In other tests FMT_ASSERT is made to throw\n// an exception which is much faster and easier to check.\n//\n// Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors\n// All rights reserved.\n//\n// For the license information refer to format.h.\n\n#include \"fmt/base.h\"\n#include \"gtest/gtest.h\"\n\nTEST(assert_test, fail) {\n#if GTEST_HAS_DEATH_TEST\n EXPECT_DEBUG_DEATH(FMT_ASSERT(false, \"don't panic!\"), \"don't panic!\");\n#else\n fmt::print(\"warning: death tests are not supported\\n\");\n#endif\n}\n\nTEST(assert_test, dangling_else) {\n bool test_condition = false;\n bool executed_else = false;\n if (test_condition)\n FMT_ASSERT(true, \"\");\n else\n executed_else = true;\n EXPECT_TRUE(executed_else);\n}", "messages": null, "tools": null} {"id": "00ae18ad196f671a", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/ssr/__tests__/ssr.spec.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 2409, "sha256": "9fd278fb052cfb47d01991452313838905a5fe246954e0874212a43970d4ae70", "text": "import { expect, test } from 'vitest'\nimport { port, serverLogs } from './serve'\nimport { browserLogs, editFile, isServe, page } from '~utils'\n\nconst url = `http://localhost:${port}`\n\ntest(`circular dependencies modules doesn't throw`, async () => {\n await page.goto(`${url}/circular-dep`)\n\n expect(await page.textContent('.circ-dep-init')).toMatch(\n 'circ-dep-init-a circ-dep-init-b',\n )\n})\n\ntest(`circular import doesn't throw (1)`, async () => {\n await page.goto(`${url}/circular-import`)\n\n expect(await page.textContent('.circ-import')).toMatchInlineSnapshot(\n '\"A is: __A__\"',\n )\n})\n\ntest(`circular import doesn't throw (2)`, async () => {\n await page.goto(`${url}/circular-import2`)\n\n expect(await page.textContent('.circ-import')).toMatchInlineSnapshot(\n '\"A is: __A__\"',\n )\n})\n\ntest(`deadlock doesn't happen for static imports`, async () => {\n await page.goto(`${url}/forked-deadlock-static-imports`)\n\n expect(await page.textContent('.forked-deadlock-static-imports')).toMatch(\n 'rendered',\n )\n})\n\ntest(`deadlock doesn't happen for dynamic imports`, async () => {\n await page.goto(`${url}/forked-deadlock-dynamic-imports`)\n\n expect(await page.textContent('.forked-deadlock-dynamic-imports')).toMatch(\n 'rendered',\n )\n})\n\ntest(`import.meta.resolve is supported`, async () => {\n await page.goto(`${url}/import-meta`)\n\n const metaUrl = await page.textContent('.import-meta-url')\n expect(metaUrl).not.toBe('')\n expect(await page.textContent('.import-meta-resolve')).toBe(metaUrl)\n})\n\ntest(`import.meta.main is supported`, async () => {\n await page.goto(`${url}/import-meta`)\n\n expect(await page.textContent('.import-meta-main')).toBe('false')\n})\n\ntest.runIf(isServe)('html proxy is encoded', async () => {\n await page.goto(\n `${url}?%22%3E%3C/script%3E%3Cscript%3Econsole.log(%27html%20proxy%20is%20not%20encoded%27)%3C/script%3E`,\n )\n\n expect(browserLogs).not.toContain('html proxy is not encoded')\n})\n\n// run this at the end to reduce flakiness\ntest.runIf(isServe)('should restart ssr', async () => {\n editFile('./vite.config.ts', (content) => content + '\\n')\n await expect\n .poll(() => {\n expect(serverLogs).toEqual(\n expect.arrayContaining([expect.stringMatching('server restarted')]),\n )\n expect(serverLogs).not.toEqual(\n expect.arrayContaining([expect.stringMatching('error')]),\n )\n })\n .toSatisfy(() => true)\n})", "messages": null, "tools": null} {"id": "011477fc301bab4e", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/create-vite/template-svelte-ts/README.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 3081, "sha256": "11d68750c734474bb51754136f4249600c385f9a4851043380dfd3741cb6559e", "text": "# Svelte + TS + Vite\n\nThis template should help get you started developing with Svelte and TypeScript in Vite.\n\n## Recommended IDE Setup\n\n[VS Code](https://code.visualstudio.com/) + [Svelte](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode).\n\n## Need an official Svelte framework?\n\nCheck out [SvelteKit](https://github.com/sveltejs/kit#readme), which is also powered by Vite. Deploy anywhere with its serverless-first approach and adapt to various platforms, with out of the box support for TypeScript, SCSS, and Less, and easily-added support for mdsvex, GraphQL, PostCSS, Tailwind CSS, and more.\n\n## Technical considerations\n\n**Why use this over SvelteKit?**\n\n- It brings its own routing solution which might not be preferable for some users.\n- It is first and foremost a framework that just happens to use Vite under the hood, not a Vite app.\n\nThis template contains as little as possible to get started with Vite + TypeScript + Svelte, while taking into account the developer experience with regards to HMR and intellisense. It demonstrates capabilities on par with the other `create-vite` templates and is a good starting point for beginners dipping their toes into a Vite + Svelte project.\n\nShould you later need the extended capabilities and extensibility provided by SvelteKit, the template has been structured similarly to SvelteKit so that it is easy to migrate.\n\n**Why `global.d.ts` instead of `compilerOptions.types` inside `jsconfig.json` or `tsconfig.json`?**\n\nSetting `compilerOptions.types` shuts out all other types not explicitly listed in the configuration. Using triple-slash references keeps the default TypeScript setting of accepting type information from the entire workspace, while also adding `svelte` and `vite/client` type information.\n\n**Why include `.vscode/extensions.json`?**\n\nOther templates indirectly recommend extensions via the README, but this file allows VS Code to prompt the user to install the recommended extension upon opening the project.\n\n**Why enable `allowJs` in the TS template?**\n\nWhile `allowJs: false` would indeed prevent the use of `.js` files in the project, it does not prevent the use of JavaScript syntax in `.svelte` files. In addition, it would force `checkJs: false`, bringing the worst of both worlds: not being able to guarantee the entire codebase is TypeScript, and also having worse typechecking for the existing JavaScript. In addition, there are valid use cases in which a mixed codebase may be relevant.\n\n**Why is HMR not preserving my local component state?**\n\nHMR state preservation comes with a number of gotchas! It has been disabled by default in both `svelte-hmr` and `@sveltejs/vite-plugin-svelte` due to its often surprising behavior. You can read the details [here](https://github.com/rixo/svelte-hmr#svelte-hmr).\n\nIf you have state that's important to retain within a component, consider creating an external store which would not be replaced by HMR.\n\n```ts\n// store.ts\n// An extremely simple external store\nimport { writable } from 'svelte/store'\nexport default writable(0)\n```", "messages": null, "tools": null} {"id": "01313506bfa6f9a4", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/thirdparty/Fuzzer/FuzzerMerge.h", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 2489, "sha256": "16552b3275a68080ce2af038f2c0a862c9f4f0ccde54ba8d306b5086437da3ec", "text": "//===- FuzzerMerge.h - merging corpa ----------------------------*- C++ -* ===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n// Merging Corpora.\n//\n// The task:\n// Take the existing corpus (possibly empty) and merge new inputs into\n// it so that only inputs with new coverage ('features') are added.\n// The process should tolerate the crashes, OOMs, leaks, etc.\n//\n// Algorithm:\n// The outter process collects the set of files and writes their names\n// into a temporary \"control\" file, then repeatedly launches the inner\n// process until all inputs are processed.\n// The outer process does not actually execute the target code.\n//\n// The inner process reads the control file and sees a) list of all the inputs\n// and b) the last processed input. Then it starts processing the inputs one\n// by one. Before processing every input it writes one line to control file:\n// STARTED INPUT_ID INPUT_SIZE\n// After processing an input it write another line:\n// DONE INPUT_ID Feature1 Feature2 Feature3 ...\n// If a crash happens while processing an input the last line in the control\n// file will be \"STARTED INPUT_ID\" and so the next process will know\n// where to resume.\n//\n// Once all inputs are processed by the innner process(es) the outer process\n// reads the control files and does the merge based entirely on the contents\n// of control file.\n// It uses a single pass greedy algorithm choosing first the smallest inputs\n// within the same size the inputs that have more new features.\n//\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_FUZZER_MERGE_H\n#define LLVM_FUZZER_MERGE_H\n\n#include \"FuzzerDefs.h\"\n\n#include \n#include \n\nnamespace fuzzer {\n\nstruct MergeFileInfo {\n std::string Name;\n size_t Size = 0;\n std::vector Features;\n};\n\nstruct Merger {\n std::vector Files;\n size_t NumFilesInFirstCorpus = 0;\n size_t FirstNotProcessedFile = 0;\n std::string LastFailure;\n\n bool Parse(std::istream &IS, bool ParseCoverage);\n bool Parse(const std::string &Str, bool ParseCoverage);\n void ParseOrExit(std::istream &IS, bool ParseCoverage);\n size_t Merge(std::vector *NewFiles);\n};\n\n} // namespace fuzzer\n\n#endif // LLVM_FUZZER_MERGE_H", "messages": null, "tools": null} {"id": "017b729c50c6fce8", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "include/nlohmann/detail/exceptions.hpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 10586, "sha256": "c400a5e907a74b82beead75cecc09be15ea387a6070e5dd61fcb6a740221713a", "text": "// __ _____ _____ _____\n// __| | __| | | | JSON for Modern C++\n// | | |__ | | | | | | version 3.12.0\n// |_____|_____|_____|_|___| https://github.com/nlohmann/json\n//\n// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann \n// SPDX-License-Identifier: MIT\n\n#pragma once\n\n#include // nullptr_t\n#include // exception\n#if JSON_DIAGNOSTICS\n #include // accumulate\n#endif\n#include // runtime_error\n#include // to_string\n#include // vector\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n// With -Wweak-vtables, Clang will complain about the exception classes as they\n// have no out-of-line virtual method definitions and their vtable will be\n// emitted in every translation unit. This issue cannot be fixed with a\n// header-only library as there is no implementation file to move these\n// functions to. As a result, we suppress this warning here to avoid client\n// code stumbling over this. See https://github.com/nlohmann/json/issues/4087\n// for a discussion.\n#if defined(__clang__)\n #pragma clang diagnostic push\n #pragma clang diagnostic ignored \"-Wweak-vtables\"\n#endif\n\nNLOHMANN_JSON_NAMESPACE_BEGIN\nnamespace detail\n{\n\n////////////////\n// exceptions //\n////////////////\n\n/// @brief general exception of the @ref basic_json class\n/// @sa https://json.nlohmann.me/api/basic_json/exception/\nclass exception : public std::exception\n{\n public:\n /// returns the explanatory string\n const char* what() const noexcept override\n {\n return m.what();\n }\n\n /// the id of the exception\n const int id; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes)\n\n protected:\n JSON_HEDLEY_NON_NULL(3)\n exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} // NOLINT(bugprone-throw-keyword-missing)\n\n static std::string name(const std::string& ename, int id_)\n {\n return concat(\"[json.exception.\", ename, '.', std::to_string(id_), \"] \");\n }\n\n static std::string diagnostics(std::nullptr_t /*leaf_element*/)\n {\n return \"\";\n }\n\n template\n static std::string diagnostics(const BasicJsonType* leaf_element)\n {\n#if JSON_DIAGNOSTICS\n std::vector tokens;\n for (const auto* current = leaf_element; current != nullptr && current->m_parent != nullptr; current = current->m_parent)\n {\n switch (current->m_parent->type())\n {\n case value_t::array:\n {\n for (std::size_t i = 0; i < current->m_parent->m_data.m_value.array->size(); ++i)\n {\n if (¤t->m_parent->m_data.m_value.array->operator[](i) == current)\n {\n tokens.emplace_back(std::to_string(i));\n break;\n }\n }\n break;\n }\n\n case value_t::object:\n {\n for (const auto& element : *current->m_parent->m_data.m_value.object)\n {\n if (&element.second == current)\n {\n tokens.emplace_back(element.first.c_str());\n break;\n }\n }\n break;\n }\n\n case value_t::null: // LCOV_EXCL_LINE\n case value_t::string: // LCOV_EXCL_LINE\n case value_t::boolean: // LCOV_EXCL_LINE\n case value_t::number_integer: // LCOV_EXCL_LINE\n case value_t::number_unsigned: // LCOV_EXCL_LINE\n case value_t::number_float: // LCOV_EXCL_LINE\n case value_t::binary: // LCOV_EXCL_LINE\n case value_t::discarded: // LCOV_EXCL_LINE\n default: // LCOV_EXCL_LINE\n break; // LCOV_EXCL_LINE\n }\n }\n\n if (tokens.empty())\n {\n return \"\";\n }\n\n auto str = std::accumulate(tokens.rbegin(), tokens.rend(), std::string{},\n [](const std::string & a, const std::string & b)\n {\n return concat(a, '/', detail::escape(b));\n });\n\n return concat('(', str, \") \", get_byte_positions(leaf_element));\n#else\n return get_byte_positions(leaf_element);\n#endif\n }\n\n private:\n /// an exception object as storage for error messages\n std::runtime_error m;\n#if JSON_DIAGNOSTIC_POSITIONS\n template\n static std::string get_byte_positions(const BasicJsonType* leaf_element)\n {\n if ((leaf_element->start_pos() != std::string::npos) && (leaf_element->end_pos() != std::string::npos))\n {\n return concat(\"(bytes \", std::to_string(leaf_element->start_pos()), \"-\", std::to_string(leaf_element->end_pos()), \") \");\n }\n return \"\";\n }\n#else\n template\n static std::string get_byte_positions(const BasicJsonType* leaf_element)\n {\n static_cast(leaf_element);\n return \"\";\n }\n#endif\n};\n\n/// @brief exception indicating a parse error\n/// @sa https://json.nlohmann.me/api/basic_json/parse_error/\nclass parse_error : public exception\n{\n public:\n /*!\n @brief create a parse error exception\n @param[in] id_ the id of the exception\n @param[in] pos the position where the error occurred (or with\n chars_read_total=0 if the position cannot be\n determined)\n @param[in] what_arg the explanatory string\n @return parse_error object\n */\n template::value, int> = 0>\n static parse_error create(int id_, const position_t& pos, const std::string& what_arg, BasicJsonContext context)\n {\n const std::string w = concat(exception::name(\"parse_error\", id_), \"parse error\",\n position_string(pos), \": \", exception::diagnostics(context), what_arg);\n return {id_, pos.chars_read_total, w.c_str()};\n }\n\n template::value, int> = 0>\n static parse_error create(int id_, std::size_t byte_, const std::string& what_arg, BasicJsonContext context)\n {\n const std::string w = concat(exception::name(\"parse_error\", id_), \"parse error\",\n (byte_ != 0 ? (concat(\" at byte \", std::to_string(byte_))) : \"\"),\n \": \", exception::diagnostics(context), what_arg);\n return {id_, byte_, w.c_str()};\n }\n\n /*!\n @brief byte index of the parse error\n\n The byte index of the last read character in the input file.\n\n @note For an input with n bytes, 1 is the index of the first character and\n n+1 is the index of the terminating null byte or the end of file.\n This also holds true when reading a byte vector (CBOR or MessagePack).\n */\n const std::size_t byte;\n\n private:\n parse_error(int id_, std::size_t byte_, const char* what_arg)\n : exception(id_, what_arg), byte(byte_) {}\n\n static std::string position_string(const position_t& pos)\n {\n return concat(\" at line \", std::to_string(pos.lines_read + 1),\n \", column \", std::to_string(pos.chars_read_current_line));\n }\n};\n\n/// @brief exception indicating errors with iterators\n/// @sa https://json.nlohmann.me/api/basic_json/invalid_iterator/\nclass invalid_iterator : public exception\n{\n public:\n template::value, int> = 0>\n static invalid_iterator create(int id_, const std::string& what_arg, BasicJsonContext context)\n {\n const std::string w = concat(exception::name(\"invalid_iterator\", id_), exception::diagnostics(context), what_arg);\n return {id_, w.c_str()};\n }\n\n private:\n JSON_HEDLEY_NON_NULL(3)\n invalid_iterator(int id_, const char* what_arg)\n : exception(id_, what_arg) {}\n};\n\n/// @brief exception indicating executing a member function with a wrong type\n/// @sa https://json.nlohmann.me/api/basic_json/type_error/\nclass type_error : public exception\n{\n public:\n template::value, int> = 0>\n static type_error create(int id_, const std::string& what_arg, BasicJsonContext context)\n {\n const std::string w = concat(exception::name(\"type_error\", id_), exception::diagnostics(context), what_arg);\n return {id_, w.c_str()};\n }\n\n private:\n JSON_HEDLEY_NON_NULL(3)\n type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}\n};\n\n/// @brief exception indicating access out of the defined range\n/// @sa https://json.nlohmann.me/api/basic_json/out_of_range/\nclass out_of_range : public exception\n{\n public:\n template::value, int> = 0>\n static out_of_range create(int id_, const std::string& what_arg, BasicJsonContext context)\n {\n const std::string w = concat(exception::name(\"out_of_range\", id_), exception::diagnostics(context), what_arg);\n return {id_, w.c_str()};\n }\n\n private:\n JSON_HEDLEY_NON_NULL(3)\n out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}\n};\n\n/// @brief exception indicating other library errors\n/// @sa https://json.nlohmann.me/api/basic_json/other_error/\nclass other_error : public exception\n{\n public:\n template::value, int> = 0>\n static other_error create(int id_, const std::string& what_arg, BasicJsonContext context)\n {\n const std::string w = concat(exception::name(\"other_error\", id_), exception::diagnostics(context), what_arg);\n return {id_, w.c_str()};\n }\n\n private:\n JSON_HEDLEY_NON_NULL(3)\n other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}\n};\n\n} // namespace detail\nNLOHMANN_JSON_NAMESPACE_END\n\n#if defined(__clang__)\n #pragma clang diagnostic pop\n#endif", "messages": null, "tools": null} {"id": "017cfe2ea509e3fe", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/guide/api-environment-plugins.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 14648, "sha256": "a9b7f4d6cbfa6e404959ed56ae3a27a2fda8699c692ef833c98a46a57400646a", "text": "# Environment API for Plugins\n\n:::info Release Candidate\nThe Environment API is generally in the release candidate phase. We'll maintain stability in the APIs between major releases to allow the ecosystem to experiment and build upon them. However, note that [some specific APIs](/changes/#considering) are still considered experimental.\n\nWe plan to stabilize these new APIs (with potential breaking changes) in a future major release once downstream projects have had time to experiment with the new features and validate them.\n\nResources:\n\n- [Feedback discussion](https://github.com/vitejs/vite/discussions/16358) where we are gathering feedback about the new APIs.\n- [Environment API PR](https://github.com/vitejs/vite/pull/16471) where the new APIs were implemented and reviewed.\n\nPlease share your feedback with us.\n:::\n\n## Per-environment Hooks and Global Hooks\n\nPlugins run on a shared pipeline, but their hooks fall into two categories depending on whether they run once for the whole server or once for each environment.\n\nGlobal hooks are called a single time, independent of the configured environments. They handle app-wide concerns such as resolving the config or setting up the dev and preview servers, so `this.environment` is not relevant to them. Config resolution related hooks and server related hooks are global hooks.\n\nPer-environment hooks are called once for each environment, and expose the current environment through `this.environment` in their context. All [Rolldown hooks](/guide/api-plugin#rolldown-hooks) are per-environment, as are other Vite-specific hooks that handle modules. However, note that `buildStart` and `buildEnd` are only called for the client environment without [the `perEnvironmentStartEndDuringDev: true` flag](#per-environment-state-in-plugins).\n\n## Accessing the Current Environment in Hooks\n\nGiven that there were only two Environments until Vite 6 (`client` and `ssr`), a `ssr` boolean was enough to identify the current environment in Vite APIs. Plugin Hooks received a `ssr` boolean in the last options parameter, and several APIs expected an optional last `ssr` parameter to properly associate modules to the correct environment (for example `server.moduleGraph.getModuleByUrl(url, { ssr })`).\n\nWith the advent of configurable environments, we now have a uniform way to access their options and instance in plugins. Plugin hooks now expose `this.environment` in their context, and APIs that previously expected a `ssr` boolean are now scoped to the proper environment (for example `environment.moduleGraph.getModuleByUrl(url)`).\n\nThe Vite server has a shared plugin pipeline, but when a module is processed it is always done in the context of a given environment. The `environment` instance is available in the plugin context.\n\nA plugin could use the `environment` instance to change how a module is processed depending on the configuration for the environment (which can be accessed using `environment.config`).\n\n```ts\n transform(code, id) {\n console.log(this.environment.config.resolve.conditions)\n }\n```\n\n## Registering New Environments Using Hooks\n\nPlugins can add new environments in the `config` hook. For example, [RSC support](/plugins/#vitejs-plugin-rsc) uses an additional environment to have a separate module graph with the `react-server` condition:\n\n```ts\n config(config: UserConfig) {\n return {\n environments: {\n rsc: {\n resolve: {\n conditions: ['react-server', ...defaultServerConditions],\n },\n },\n },\n }\n }\n```\n\nAn empty object is enough to register the environment, using default values from the root level environment config.\n\n## Configuring Environment Using the `configEnvironment` Hook\n\n- **Type:** `(name: string, config: EnvironmentOptions, env: { mode: string, command: 'build' | 'serve', isSsrBuild?: boolean, isPreview?: boolean, isSsrTargetWebworker?: boolean }) => EnvironmentOptions | null | void`\n- **Kind:** `async`, `sequential`\n- **Scope:** [Per-environment](#per-environment-hooks-and-global-hooks)\n\nWhile the `config` hook is running, the complete list of environments isn't yet known and the environments can be affected by both the default values from the root level environment config or explicitly through the `config.environments` record.\nPlugins should set default values using the `config` hook. To configure each environment, they can use the new `configEnvironment` hook. This hook is called for each environment with its partially resolved config including resolution of final defaults.\n\n```ts\n configEnvironment(name: string, options: EnvironmentOptions) {\n // add \"workerd\" condition to the rsc environment\n if (name === 'rsc') {\n return {\n resolve: {\n conditions: ['workerd'],\n },\n }\n }\n }\n```\n\n## The `hotUpdate` Hook\n\n- **Type:** `(this: { environment: DevEnvironment }, options: HotUpdateOptions) => Array | void | Promise | void>`\n- **Kind:** `async`, `sequential`\n- **Scope:** [Per-environment](#per-environment-hooks-and-global-hooks)\n- **See also:** [HMR API](./api-hmr)\n\nThe `hotUpdate` hook allows plugins to perform custom HMR update handling for a given environment. When a file changes, the HMR algorithm is run for each environment in series according to the order in `server.environments`, so the `hotUpdate` hook will be called multiple times. The hook receives a context object with the following signature:\n\n```ts\ninterface HotUpdateOptions {\n type: 'create' | 'update' | 'delete'\n file: string\n timestamp: number\n modules: Array\n read: () => string | Promise\n server: ViteDevServer\n}\n```\n\n- `this.environment` is the module execution environment where a file update is currently being processed.\n\n- `modules` is an array of modules in this environment that are affected by the changed file. It's an array because a single file may map to multiple served modules (e.g. Vue SFCs).\n\n- `read` is an async read function that returns the content of the file. This is provided because, on some systems, the file change callback may fire too fast before the editor finishes updating the file, and direct `fs.readFile` will return empty content. The read function passed in normalizes this behavior.\n\nThe hook can choose to:\n\n- Filter and narrow down the affected module list so that the HMR is more accurate.\n\n- Return an empty array and perform a full reload:\n\n ```js\n hotUpdate({ modules, timestamp }) {\n if (this.environment.name !== 'client')\n return\n\n // Invalidate modules manually\n const invalidatedModules = new Set()\n for (const mod of modules) {\n this.environment.moduleGraph.invalidateModule(\n mod,\n invalidatedModules,\n timestamp,\n true\n )\n }\n this.environment.hot.send({ type: 'full-reload' })\n return []\n }\n ```\n\n- Return an empty array and perform complete custom HMR handling by sending custom events to the client:\n\n ```js\n hotUpdate() {\n if (this.environment.name !== 'client')\n return\n\n this.environment.hot.send({\n type: 'custom',\n event: 'special-update',\n data: {}\n })\n return []\n }\n ```\n\n Client code should register the corresponding handler using the [HMR API](./api-hmr) (this could be injected by the same plugin's `transform` hook):\n\n ```js\n if (import.meta.hot) {\n import.meta.hot.on('special-update', (data) => {\n // perform custom update\n })\n }\n ```\n\n## Per-environment State in Plugins\n\nGiven that the same plugin instance is used for different environments, the plugin state needs to be keyed with `this.environment`. This is the same pattern the ecosystem has already been using to keep state about modules using the `ssr` boolean as key to avoid mixing client and ssr modules state. A `Map` can be used to keep the state for each environment separately. Note that for backward compatibility, `buildStart` and `buildEnd` are only called for the client environment without the `perEnvironmentStartEndDuringDev: true` flag. Same for `watchChange` and the `perEnvironmentWatchChangeDuringDev: true` flag.\n\n```js\nfunction PerEnvironmentCountTransformedModulesPlugin() {\n const state = new Map()\n return {\n name: 'count-transformed-modules',\n perEnvironmentStartEndDuringDev: true,\n buildStart() {\n state.set(this.environment, { count: 0 })\n },\n transform(id) {\n state.get(this.environment).count++\n },\n buildEnd() {\n console.log(this.environment.name, state.get(this.environment).count)\n }\n }\n}\n```\n\n## Per-environment Plugins Using the `applyToEnvironment` Hook\n\n- **Type:** `(environment: PartialEnvironment) => boolean | PluginOption | Promise`\n- **Kind:** `async`, `sequential`\n- **Scope:** [Per-environment](#per-environment-hooks-and-global-hooks)\n\nA plugin can define what are the environments it should apply to with the `applyToEnvironment` function.\n\n```js\nconst UnoCssPlugin = () => {\n // shared global state\n return {\n buildStart() {\n // init per-environment state with WeakMap\n // using this.environment\n },\n configureServer() {\n // use global hooks normally\n },\n applyToEnvironment(environment) {\n // return true if this plugin should be active in this environment,\n // or return a new plugin to replace it.\n // if the hook is not used, the plugin is active in all environments\n },\n resolveId(id, importer) {\n // only called for environments this plugin apply to\n },\n }\n}\n```\n\nIf a plugin isn't environment aware and has state that isn't keyed on the current environment, the `applyToEnvironment` hook allows to easily make it per-environment.\n\n```js\nimport { nonShareablePlugin } from 'non-shareable-plugin'\n\nexport default defineConfig({\n plugins: [\n {\n name: 'per-environment-plugin',\n applyToEnvironment(environment) {\n return nonShareablePlugin({ outputName: environment.name })\n },\n },\n ],\n})\n```\n\nVite exports a `perEnvironmentPlugin` helper to simplify these cases where no other hooks are required:\n\n```js\nimport { nonShareablePlugin } from 'non-shareable-plugin'\n\nexport default defineConfig({\n plugins: [\n perEnvironmentPlugin('per-environment-plugin', (environment) =>\n nonShareablePlugin({ outputName: environment.name }),\n ),\n ],\n})\n```\n\nThe `applyToEnvironment` hook is called at config time, currently after `configResolved` due to projects in the ecosystem modifying the plugins in it. Environment plugins resolution may be moved before `configResolved` in the future.\n\n## Application-Plugin Communication\n\n`environment.hot` allows plugins to communicate with the code on the application side for a given environment. This is the equivalent of [the Client-server Communication feature](/guide/api-plugin#client-server-communication), but supports environments other than the client environment.\n\n:::warning Note\n\nNote that this feature is only available for environments that support HMR.\n\n:::\n\n### Managing the Application Instances\n\nBe aware that there might be multiple application instances running in the same environment. For example, if you have multiple tabs open in the browser, each tab is a separate application instance and has a separate connection to the server.\n\nWhen a new connection is established, a `vite:client:connect` event is emitted on the environment's `hot` instance. When the connection is closed, a `vite:client:disconnect` event is emitted.\n\nEach event handler receives the `NormalizedHotChannelClient` as the second argument. The client is an object with a `send` method that can be used to send messages to that specific application instance. The client reference is always the same for the same connection, so you can keep it to track the connection.\n\n### Example Usage\n\nThe plugin side:\n\n```js\nconfigureServer(server) {\n server.environments.ssr.hot.on('my:greetings', (data, client) => {\n // do something with the data,\n // and optionally send a response to that application instance\n client.send('my:foo:reply', `Hello from server! You said: ${data}`)\n })\n\n // broadcast a message to all application instances\n server.environments.ssr.hot.send('my:foo', 'Hello from server!')\n}\n```\n\nThe application side is same with the Client-server Communication feature. You can use the `import.meta.hot` object to send messages to the plugin.\n\n## Environment in Build Hooks\n\nIn the same way as during dev, plugin hooks also receive the environment instance during build, replacing the `ssr` boolean.\nThis also works for `renderChunk`, `generateBundle`, and other build only hooks.\n\n## Shared Plugins During Build\n\nBefore Vite 6, the plugins pipelines worked in a different way during dev and build:\n\n- **During dev:** plugins are shared\n- **During Build:** plugins are isolated for each environment (in different processes: `vite build` then `vite build --ssr`).\n\nThis forced frameworks to share state between the `client` build and the `ssr` build through manifest files written to the file system. In Vite 6, we are now building all environments in a single process so the way the plugins pipeline and inter-environment communication can be aligned with dev.\n\nIn a future major, we could have complete alignment:\n\n- **During both dev and build:** plugins are shared, with [per-environment filtering](#per-environment-plugins-using-the-applytoenvironment-hook)\n\nThere will also be a single `ResolvedConfig` instance shared during build, allowing for caching at entire app build process level in the same way as we have been doing with `WeakMap` during dev.\n\nFor Vite 6, we need to do a smaller step to keep backward compatibility. Ecosystem plugins are currently using `config.build` instead of `environment.config.build` to access configuration, so we need to create a new `ResolvedConfig` per-environment by default. A project can opt-in into sharing the full config and plugins pipeline setting `builder.sharedConfigBuild` to `true`.\n\nThis option would only work of a small subset of projects at first, so plugin authors can opt-in for a particular plugin to be shared by setting the `sharedDuringBuild` flag to `true`. This allows for easily sharing state both for regular plugins:\n\n```js\nfunction myPlugin() {\n // Share state among all environments in dev and build\n const sharedState = ...\n return {\n name: 'shared-plugin',\n transform(code, id) { ... },\n\n // Opt-in into a single instance for all environments\n sharedDuringBuild: true,\n }\n}\n```", "messages": null, "tools": null} {"id": "019889027b8d6c03", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/node/__tests__/plugins/importGlob/fixture-a/index.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 3434, "sha256": "3415b5482303fe5817b8790507fc86d09589935828f755a1305d26826cf0075d", "text": "// NOTE: `#types/importMeta` does not work as `src/node/__tests__/package.json` shadows the root\n// `package.json` and does not declare the subpath import.\nimport '../../../../../../types/importMeta'\n\nexport interface ModuleType {\n name: string\n}\n\nexport const basic = import.meta.glob('./modules/*.ts')\n// prettier-ignore\nexport const basicWithObjectKeys = Object.keys(import.meta.glob('./modules/*.ts'))\n// prettier-ignore\nexport const basicWithObjectValues = Object.values(import.meta.glob('./modules/*.ts'))\n\nexport const basicEager = import.meta.glob('./modules/*.ts', {\n eager: true,\n})\nexport const basicEagerWithObjectKeys = Object.keys(\n import.meta.glob('./modules/*.ts', {\n eager: true,\n }),\n)\nexport const basicEagerWithObjectValues = Object.values(\n import.meta.glob('./modules/*.ts', {\n eager: true,\n }),\n)\n\nexport const ignore = import.meta.glob(['./modules/*.ts', '!**/index.ts'])\nexport const ignoreWithObjectKeys = Object.keys(\n import.meta.glob(['./modules/*.ts', '!**/index.ts']),\n)\nexport const ignoreWithObjectValues = Object.values(\n import.meta.glob(['./modules/*.ts', '!**/index.ts']),\n)\n\nexport const namedEager = import.meta.glob('./modules/*.ts', {\n eager: true,\n import: 'name',\n})\nexport const namedEagerWithObjectKeys = Object.keys(\n import.meta.glob('./modules/*.ts', {\n eager: true,\n import: 'name',\n }),\n)\nexport const namedEagerWithObjectValues = Object.values(\n import.meta.glob('./modules/*.ts', {\n eager: true,\n import: 'name',\n }),\n)\n\nexport const namedDefault = import.meta.glob('./modules/*.ts', {\n import: 'default',\n})\nexport const namedDefaultWithObjectKeys = Object.keys(\n import.meta.glob('./modules/*.ts', {\n import: 'default',\n }),\n)\nexport const namedDefaultWithObjectValues = Object.values(\n import.meta.glob('./modules/*.ts', {\n import: 'default',\n }),\n)\n\nexport const eagerAs = import.meta.glob(\n ['./modules/*.ts', '!**/index.ts'],\n { eager: true, query: '?raw', import: 'default' },\n)\n\nexport const rawImportModule = import.meta.glob(\n ['./modules/*.ts', '!**/index.ts'],\n { query: '?raw', import: '*' },\n)\n\nexport const excludeSelf = import.meta.glob(\n './*.ts',\n // for test: annotation contain \")\"\n /*\n * for test: annotation contain \")\"\n * */\n)\nexport const excludeSelfRaw = import.meta.glob('./*.ts', { query: '?raw' })\n\nexport const customQueryString = import.meta.glob('./*.ts', { query: 'custom' })\n\nexport const customQueryObject = import.meta.glob('./*.ts', {\n query: {\n foo: 'bar',\n raw: true,\n },\n})\n\nexport const parent = import.meta.glob('../../playground/src/*.ts', {\n query: '?url',\n import: 'default',\n})\n\nexport const rootMixedRelative = import.meta.glob(\n ['/*.ts', '../fixture-b/*.ts'],\n { query: '?url', import: 'default' },\n)\n\nexport const cleverCwd1 = import.meta.glob(\n './node_modules/framework/**/*.page.js',\n)\n\nexport const cleverCwd2 = import.meta.glob([\n './modules/*.ts',\n '../fixture-b/*.ts',\n '!**/index.ts',\n])\n\nexport const customBase = import.meta.glob('./**/*.ts', { base: './' })\n\nexport const customRootBase = import.meta.glob('./**/*.ts', {\n base: '/fixture-b',\n})\n\nexport const customBaseParent = import.meta.glob('/fixture-b/**/*.ts', {\n base: '/fixture-a',\n})\n\nexport const dotFolder = import.meta.glob('./.foo/*.ts', { eager: true })", "messages": null, "tools": null} {"id": "01a6c4293284bf76", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/node/plugin.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 14318, "sha256": "a7f23c9ec06a7914ce0fcaee6bdb0284bad728aead00e0e48009de7c81449eb8", "text": "import type {\n CustomPluginOptions,\n ImportKind,\n LoadResult,\n MinimalPluginContext,\n ModuleType,\n ModuleTypeFilter,\n ObjectHook,\n PluginContext,\n PluginContextMeta,\n ResolveIdResult,\n Plugin as RolldownPlugin,\n TransformPluginContext,\n TransformResult,\n} from 'rolldown'\nimport type {\n ConfigEnv,\n EnvironmentOptions,\n ResolvedConfig,\n UserConfig,\n} from './config'\nimport type { ServerHook } from './server'\nimport type { BuildAppHook } from './build'\nimport type { IndexHtmlTransform } from './plugins/html'\nimport type { EnvironmentModuleNode } from './server/moduleGraph'\nimport type { ModuleNode } from './server/mixedModuleGraph'\nimport type { HmrContext, HotUpdateOptions } from './server/hmr'\nimport type { DevEnvironment } from './server/environment'\nimport type { Environment } from './environment'\nimport type { PartialEnvironment } from './baseEnvironment'\nimport type { PreviewServerHook } from './preview'\nimport { arraify, asyncFlatten } from './utils'\nimport type { StringFilter } from './plugins/pluginFilter'\n\n/**\n * Vite plugins extends the Rollup plugin interface with a few extra\n * vite-specific options. A valid vite plugin is also a valid Rollup plugin.\n * On the contrary, a Rollup plugin may or may NOT be a valid vite universal\n * plugin, since some Rollup features do not make sense in an unbundled\n * dev server context. That said, as long as a rollup plugin doesn't have strong\n * coupling between its bundle phase and output phase hooks then it should\n * just work (that means, most of them).\n *\n * By default, the plugins are run during both serve and build. When a plugin\n * is applied during serve, it will only run **non output plugin hooks** (see\n * rollup type definition of {@link rollup#PluginHooks}). You can think of the\n * dev server as only running `const bundle = rollup.rollup()` but never calling\n * `bundle.generate()`.\n *\n * A plugin that expects to have different behavior depending on serve/build can\n * export a factory function that receives the command being run via options.\n *\n * If a plugin should be applied only for server or build, a function format\n * config file can be used to conditional determine the plugins to use.\n *\n * The current environment can be accessed from the context for the all non-global\n * hooks (it is not available in config, configResolved, configureServer, etc).\n * It can be a dev, build, or scan environment.\n * Plugins can use this.environment.mode === 'dev' to guard for dev specific APIs.\n */\n\nexport interface PluginContextExtension {\n /**\n * Vite-specific environment instance\n */\n environment: Environment\n}\n\nexport interface PluginContextMetaExtension {\n viteVersion: string\n}\n\nexport interface ConfigPluginContext extends Omit<\n MinimalPluginContext,\n 'meta' | 'environment'\n> {\n meta: Omit\n}\n\nexport interface MinimalPluginContextWithoutEnvironment extends Omit<\n MinimalPluginContext,\n 'environment'\n> {}\n\n// Augment Rolldown types to have the PluginContextExtension\ndeclare module 'rolldown' {\n export interface MinimalPluginContext extends PluginContextExtension {}\n export interface PluginContextMeta extends PluginContextMetaExtension {}\n}\n\n/**\n * There are two types of plugins in Vite. App plugins and environment plugins.\n * Environment Plugins are defined by a constructor function that will be called\n * once per each environment allowing users to have completely different plugins\n * for each of them. The constructor gets the resolved environment after the server\n * and builder has already been created simplifying config access and cache\n * management for environment specific plugins.\n * Environment Plugins are closer to regular rollup plugins. They can't define\n * app level hooks (like config, configResolved, configureServer, etc).\n */\nexport interface Plugin extends RolldownPlugin {\n /**\n * Perform custom handling of HMR updates.\n * The handler receives an options containing changed filename, timestamp, a\n * list of modules affected by the file change, and the dev server instance.\n *\n * - The hook can return a filtered list of modules to narrow down the update.\n * e.g. for a Vue SFC, we can narrow down the part to update by comparing\n * the descriptors.\n *\n * - The hook can also return an empty array and then perform custom updates\n * by sending a custom hmr payload via environment.hot.send().\n *\n * - If the hook doesn't return a value, the hmr update will be performed as\n * normal.\n */\n hotUpdate?: ObjectHook<\n (\n this: MinimalPluginContext & { environment: DevEnvironment },\n options: HotUpdateOptions,\n ) =>\n | Array\n | void\n | Promise | void>\n >\n\n /**\n * extend hooks with ssr flag\n */\n resolveId?: ObjectHook<\n (\n this: PluginContext,\n source: string,\n importer: string | undefined,\n options: {\n kind?: ImportKind\n custom?: CustomPluginOptions\n ssr?: boolean | undefined\n /**\n * @internal\n */\n scan?: boolean | undefined\n isEntry: boolean\n },\n ) => Promise | ResolveIdResult,\n { filter?: { id?: StringFilter } }\n >\n load?: ObjectHook<\n (\n this: PluginContext,\n id: string,\n options?: {\n ssr?: boolean | undefined\n },\n ) => Promise | LoadResult,\n { filter?: { id?: StringFilter } }\n >\n transform?: ObjectHook<\n (\n this: TransformPluginContext,\n code: string,\n id: string,\n options?: {\n moduleType: ModuleType\n ssr?: boolean | undefined\n },\n ) => Promise | TransformResult,\n {\n filter?: {\n id?: StringFilter\n code?: StringFilter\n moduleType?: ModuleTypeFilter\n }\n }\n >\n /**\n * Opt-in this plugin into the shared plugins pipeline.\n * For backward-compatibility, plugins are re-recreated for each environment\n * during `vite build --app`\n * We have an opt-in per plugin, and a general `builder.sharedPlugins`\n * In a future major, we'll flip the default to be shared by default\n * @experimental\n */\n sharedDuringBuild?: boolean\n /**\n * Opt-in this plugin into per-environment buildStart and buildEnd during dev.\n * For backward-compatibility, the buildStart hook is called only once during\n * dev, for the client environment. Plugins can opt-in to be called\n * per-environment, aligning with the build hook behavior.\n * @experimental\n */\n perEnvironmentStartEndDuringDev?: boolean\n /**\n * Opt-in this plugin into per-environment watchChange during dev.\n * For backward-compatibility, the watchChange hook is called only once during\n * dev, for the client environment. Plugins can opt-in to be called\n * per-environment, aligning with the watchChange hook behavior.\n * @experimental\n */\n perEnvironmentWatchChangeDuringDev?: boolean\n /**\n * Enforce plugin invocation tier similar to webpack loaders. Hooks ordering\n * is still subject to the `order` property in the hook object.\n *\n * Plugin invocation order:\n * - alias resolution\n * - `enforce: 'pre'` plugins\n * - vite core plugins\n * - normal plugins\n * - vite build plugins\n * - `enforce: 'post'` plugins\n * - vite build post plugins\n */\n enforce?: 'pre' | 'post'\n /**\n * Apply the plugin only for serve or build, or on certain conditions.\n */\n apply?:\n | 'serve'\n | 'build'\n | ((this: void, config: UserConfig, env: ConfigEnv) => boolean)\n /**\n * Define environments where this plugin should be active\n * By default, the plugin is active in all environments\n * @experimental\n */\n applyToEnvironment?: (\n environment: PartialEnvironment,\n ) => boolean | Promise | PluginOption\n /**\n * Modify vite config before it's resolved. The hook can either mutate the\n * passed-in config directly, or return a partial config object that will be\n * deeply merged into existing config.\n *\n * Note: User plugins are resolved before running this hook so injecting other\n * plugins inside the `config` hook will have no effect.\n */\n config?: ObjectHook<\n (\n this: ConfigPluginContext,\n config: UserConfig,\n env: ConfigEnv,\n ) =>\n | Omit\n | null\n | void\n | Promise | null | void>\n >\n /**\n * Modify environment configs before it's resolved. The hook can either mutate the\n * passed-in environment config directly, or return a partial config object that will be\n * deeply merged into existing config.\n * This hook is called for each environment with a partially resolved environment config\n * that already accounts for the default environment config values set at the root level.\n * If plugins need to modify the config of a given environment, they should do it in this\n * hook instead of the config hook. Leaving the config hook only for modifying the root\n * default environment config.\n */\n configEnvironment?: ObjectHook<\n (\n this: ConfigPluginContext,\n name: string,\n config: EnvironmentOptions,\n env: ConfigEnv & {\n /**\n * Whether this environment is SSR environment and `ssr.target` is set to `'webworker'`.\n * Only intended to be used for backward compatibility.\n */\n isSsrTargetWebworker?: boolean\n },\n ) =>\n | EnvironmentOptions\n | null\n | void\n | Promise\n >\n /**\n * Use this hook to read and store the final resolved vite config.\n */\n configResolved?: ObjectHook<\n (\n this: MinimalPluginContextWithoutEnvironment,\n config: ResolvedConfig,\n ) => void | Promise\n >\n /**\n * Configure the vite server. The hook receives the {@link ViteDevServer}\n * instance. This can also be used to store a reference to the server\n * for use in other hooks.\n *\n * The hooks will be called before internal middlewares are applied. A hook\n * can return a post hook that will be called after internal middlewares\n * are applied. Hook can be async functions and will be called in series.\n */\n configureServer?: ObjectHook\n /**\n * Configure the preview server. The hook receives the {@link PreviewServer}\n * instance. This can also be used to store a reference to the server\n * for use in other hooks.\n *\n * The hooks are called before other middlewares are applied. A hook can\n * return a post hook that will be called after other middlewares are\n * applied. Hooks can be async functions and will be called in series.\n */\n configurePreviewServer?: ObjectHook\n /**\n * Transform index.html.\n * The hook receives the following arguments:\n *\n * - html: string\n * - ctx: IndexHtmlTransformContext, which contains:\n * - path: public path when served\n * - filename: filename on disk\n * - server?: ViteDevServer (only present during serve)\n * - bundle?: rollup.OutputBundle (only present during build)\n * - chunk?: rollup.OutputChunk\n * - originalUrl?: string\n *\n * It can either return a transformed string, or a list of html tag\n * descriptors that will be injected into the `` or ``.\n *\n * By default the transform is applied **after** vite's internal html\n * transform. If you need to apply the transform before vite, use an object:\n * `{ order: 'pre', handler: hook }`\n */\n transformIndexHtml?: IndexHtmlTransform\n /**\n * Build Environments\n *\n * @experimental\n */\n buildApp?: ObjectHook\n /**\n * Perform custom handling of HMR updates.\n * The handler receives a context containing changed filename, timestamp, a\n * list of modules affected by the file change, and the dev server instance.\n *\n * - The hook can return a filtered list of modules to narrow down the update.\n * e.g. for a Vue SFC, we can narrow down the part to update by comparing\n * the descriptors.\n *\n * - The hook can also return an empty array and then perform custom updates\n * by sending a custom hmr payload via server.ws.send().\n *\n * - If the hook doesn't return a value, the hmr update will be performed as\n * normal.\n */\n handleHotUpdate?: ObjectHook<\n (\n this: MinimalPluginContextWithoutEnvironment,\n ctx: HmrContext,\n ) => Array | void | Promise | void>\n >\n\n /**\n * This hook is not supported by Rolldown yet. But the type is declared for compatibility.\n *\n * @deprecated This hook is **not** deprecated. It is marked as deprecated just to make it clear that this hook is currently a no-op.\n */\n shouldTransformCachedModule?: ObjectHook<\n (\n this: PluginContext,\n options: {\n code: string\n id: string\n meta: CustomPluginOptions\n moduleSideEffects: boolean | 'no-treeshake'\n },\n ) => boolean | null | void\n >\n}\n\nexport type HookHandler = T extends ObjectHook ? H : T\n\nexport type PluginWithRequiredHook = Plugin & {\n [P in K]: NonNullable\n}\n\ntype Thenable = T | Promise\n\nexport type FalsyPlugin = false | null | undefined\n\nexport type PluginOption = Thenable<\n | Plugin\n | { name: string } // for rollup plugin compatibility\n | FalsyPlugin\n | PluginOption[]\n>\n\nexport async function resolveEnvironmentPlugins(\n environment: PartialEnvironment,\n): Promise {\n const environmentPlugins: Plugin[] = []\n for (const plugin of environment.getTopLevelConfig().plugins) {\n if (plugin.applyToEnvironment) {\n const applied = await plugin.applyToEnvironment(environment)\n if (!applied) {\n continue\n }\n if (applied !== true) {\n environmentPlugins.push(\n ...((await asyncFlatten(arraify(applied))).filter(\n Boolean,\n ) as Plugin[]),\n )\n continue\n }\n }\n environmentPlugins.push(plugin)\n }\n return environmentPlugins\n}\n\n/**\n * @experimental\n */\nexport function perEnvironmentPlugin(\n name: string,\n applyToEnvironment: (\n environment: PartialEnvironment,\n ) => boolean | Promise | PluginOption,\n): Plugin {\n return {\n name,\n applyToEnvironment,\n }\n}", "messages": null, "tools": null} {"id": "01f5c3b8e4bcc96c", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/plugin-legacy/src/snippets.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 2423, "sha256": "478707420445518bc541eae186b74b427c71e55275ddc99af2b2a70422c7a1fc", "text": "// https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc\n// DO NOT ALTER THIS CONTENT\nexport const safari10NoModuleFix: string = `!function(){var e=document,t=e.createElement(\"script\");if(!(\"noModule\"in t)&&\"onbeforeload\"in t){var n=!1;e.addEventListener(\"beforeload\",(function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute(\"nomodule\")||!n)return;e.preventDefault()}),!0),t.type=\"module\",t.src=\".\",e.head.appendChild(t),t.remove()}}();`\n\nexport const legacyPolyfillId: string = 'vite-legacy-polyfill'\nexport const legacyEntryId: string = 'vite-legacy-entry'\nexport const systemJSInlineCode: string = `System.import(document.getElementById('${legacyEntryId}').getAttribute('data-src'))`\n\nconst detectModernBrowserVarName = '__vite_is_modern_browser'\n\n/**\n * Create an inline module to detect if the browser supports import.meta.resolve\n *\n * This is an inline module to execute the code before other imports.\n * Throwing an error can prevent the browser from executing the rest of the code.\n *\n * Note that due to a bug in Safari 15.x and below, each inline module has to be unique,\n * otherwise Safari will only throw the error for the first time that module is imported.\n * https://github.com/vitejs/vite/issues/22008\n */\nconst createDetectImportMetaResolveSupportModule = (chunkId: string | null) =>\n `data:text/javascript,${chunkId != null ? `${JSON.stringify(chunkId)};` : ''}if(!import.meta.resolve)throw Error(\"import.meta.resolve not supported\")`\n\n// detect support via syntax errors\nexport const detectModernBrowserDetector: string = `import.meta.url;import(\"_\").catch(()=>1);(async function*(){})().next()`\nexport const detectModernBrowserCode: string = `import'${createDetectImportMetaResolveSupportModule(null)}';${detectModernBrowserDetector};window.${detectModernBrowserVarName}=true`\nexport const dynamicFallbackInlineCode: string = `!function(){if(window.${detectModernBrowserVarName})return;console.warn(\"vite: loading legacy chunks, syntax error above and the same error below should be ignored\");var e=document.getElementById(\"${legacyPolyfillId}\"),n=document.createElement(\"script\");n.src=e.src,n.onload=function(){${systemJSInlineCode}},document.body.appendChild(n)}();`\n\nexport const createModernChunkLegacyGuard = (chunkId: string): string =>\n `import'${createDetectImportMetaResolveSupportModule(chunkId)}';export function __vite_legacy_guard(){${detectModernBrowserDetector}};`", "messages": null, "tools": null} {"id": "023b8a5065ab99c8", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/multiple-entrypoints/entrypoints/a13.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 528, "sha256": "a5f7943c8bc0c5ed11e61b27211d918638c2f61a66c9ae153a45661c1990316f", "text": "import a14 from './a14'\nimport a15 from './a15'\nimport a16 from './a16'\nimport a17 from './a17'\nimport a18 from './a18'\nimport a19 from './a19'\nimport a20 from './a20'\nimport a21 from './a21'\nimport a22 from './a22'\nimport a23 from './a23'\nimport a24 from './a24'\n\nexport const that = () => import('./a12.js')\n\nexport function other() {\n return (\n a14() +\n a15() +\n a16() +\n a17() +\n a18() +\n a19() +\n a20() +\n a21() +\n a22() +\n a23() +\n a24()\n )\n}\n\nexport default function () {\n return 123\n}", "messages": null, "tools": null} {"id": "029ebee1a2f6ba9f", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/thirdparty/Fuzzer/FuzzerInternal.h", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 5517, "sha256": "014d926d6cc8729af07cca58652a9a3296c04ad1b86dfda1618574481362799d", "text": "//===- FuzzerInternal.h - Internal header for the Fuzzer --------*- C++ -* ===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n// Define the main class fuzzer::Fuzzer and most functions.\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_FUZZER_INTERNAL_H\n#define LLVM_FUZZER_INTERNAL_H\n\n#include \"FuzzerDefs.h\"\n#include \"FuzzerExtFunctions.h\"\n#include \"FuzzerInterface.h\"\n#include \"FuzzerOptions.h\"\n#include \"FuzzerSHA1.h\"\n#include \"FuzzerValueBitMap.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace fuzzer {\n\nusing namespace std::chrono;\n\nclass Fuzzer {\npublic:\n\n // Aggregates all available coverage measurements.\n struct Coverage {\n Coverage() { Reset(); }\n\n void Reset() {\n BlockCoverage = 0;\n CallerCalleeCoverage = 0;\n CounterBitmapBits = 0;\n CounterBitmap.clear();\n VPMap.Reset();\n }\n\n size_t BlockCoverage;\n size_t CallerCalleeCoverage;\n // Precalculated number of bits in CounterBitmap.\n size_t CounterBitmapBits;\n std::vector CounterBitmap;\n ValueBitMap VPMap;\n };\n\n Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,\n FuzzingOptions Options);\n ~Fuzzer();\n void Loop();\n void MinimizeCrashLoop(const Unit &U);\n void ShuffleAndMinimize(UnitVector *V);\n void InitializeTraceState();\n void RereadOutputCorpus(size_t MaxSize);\n\n size_t secondsSinceProcessStartUp() {\n return duration_cast(system_clock::now() - ProcessStartTime)\n .count();\n }\n\n bool TimedOut() {\n return Options.MaxTotalTimeSec > 0 &&\n secondsSinceProcessStartUp() >\n static_cast(Options.MaxTotalTimeSec);\n }\n\n size_t execPerSec() {\n size_t Seconds = secondsSinceProcessStartUp();\n return Seconds ? TotalNumberOfRuns / Seconds : 0;\n }\n\n size_t getTotalNumberOfRuns() { return TotalNumberOfRuns; }\n\n static void StaticAlarmCallback();\n static void StaticCrashSignalCallback();\n static void StaticInterruptCallback();\n\n void ExecuteCallback(const uint8_t *Data, size_t Size);\n size_t RunOne(const uint8_t *Data, size_t Size);\n\n // Merge Corpora[1:] into Corpora[0].\n void Merge(const std::vector &Corpora);\n void CrashResistantMerge(const std::vector &Args,\n const std::vector &Corpora);\n void CrashResistantMergeInternalStep(const std::string &ControlFilePath);\n // Returns a subset of 'Extra' that adds coverage to 'Initial'.\n UnitVector FindExtraUnits(const UnitVector &Initial, const UnitVector &Extra);\n MutationDispatcher &GetMD() { return MD; }\n void PrintFinalStats();\n void SetMaxInputLen(size_t MaxInputLen);\n void SetMaxMutationLen(size_t MaxMutationLen);\n void RssLimitCallback();\n\n // Public for tests.\n void ResetCoverage();\n\n bool InFuzzingThread() const { return IsMyThread; }\n size_t GetCurrentUnitInFuzzingThead(const uint8_t **Data) const;\n void TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,\n bool DuringInitialCorpusExecution);\n\n void HandleMalloc(size_t Size);\n\nprivate:\n void AlarmCallback();\n void CrashCallback();\n void InterruptCallback();\n void MutateAndTestOne();\n void ReportNewCoverage(InputInfo *II, const Unit &U);\n size_t RunOne(const Unit &U) { return RunOne(U.data(), U.size()); }\n void WriteToOutputCorpus(const Unit &U);\n void WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix);\n void PrintStats(const char *Where, const char *End = \"\\n\", size_t Units = 0);\n void PrintStatusForNewUnit(const Unit &U);\n void ShuffleCorpus(UnitVector *V);\n void AddToCorpus(const Unit &U);\n void CheckExitOnSrcPosOrItem();\n\n // Trace-based fuzzing: we run a unit with some kind of tracing\n // enabled and record potentially useful mutations. Then\n // We apply these mutations one by one to the unit and run it again.\n\n // Start tracing; forget all previously proposed mutations.\n void StartTraceRecording();\n // Stop tracing.\n void StopTraceRecording();\n\n void SetDeathCallback();\n static void StaticDeathCallback();\n void DumpCurrentUnit(const char *Prefix);\n void DeathCallback();\n\n void ResetEdgeCoverage();\n void ResetCounters();\n void PrepareCounters(Fuzzer::Coverage *C);\n bool RecordMaxCoverage(Fuzzer::Coverage *C);\n\n void AllocateCurrentUnitData();\n uint8_t *CurrentUnitData = nullptr;\n std::atomic CurrentUnitSize;\n uint8_t BaseSha1[kSHA1NumBytes]; // Checksum of the base unit.\n bool RunningCB = false;\n\n size_t TotalNumberOfRuns = 0;\n size_t NumberOfNewUnitsAdded = 0;\n\n bool HasMoreMallocsThanFrees = false;\n size_t NumberOfLeakDetectionAttempts = 0;\n\n UserCallback CB;\n InputCorpus &Corpus;\n MutationDispatcher &MD;\n FuzzingOptions Options;\n\n system_clock::time_point ProcessStartTime = system_clock::now();\n system_clock::time_point UnitStartTime, UnitStopTime;\n long TimeOfLongestUnitInSeconds = 0;\n long EpochOfLastReadOfOutputCorpus = 0;\n\n // Maximum recorded coverage.\n Coverage MaxCoverage;\n\n size_t MaxInputLen = 0;\n size_t MaxMutationLen = 0;\n\n // Need to know our own thread.\n static thread_local bool IsMyThread;\n\n bool InMergeMode = false;\n};\n\n}; // namespace fuzzer\n\n#endif // LLVM_FUZZER_INTERNAL_H", "messages": null, "tools": null} {"id": "02b1ec7a68fdd9f0", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/css-codesplit/index.html", "lang": "html", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 524, "sha256": "de2302a4ecb3fd1425dcb5b8c2479271d55545347f44a0cf6524522160a17a0f", "text": "

This should be red

\n

This should be blue

\n\n

This should be green

\n

This should be blue

\n

This should not be yellow

\n

\n

This should be yellow

\n

\n\n

\n This should be orange\n \n

\n\n

This should be magenta

\n\n\n
", "messages": null, "tools": null} {"id": "02daf676d205c92b", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/preload/__tests__/preload.spec.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 795, "sha256": "9cc320614d2d7aa74160d19df798b5544b7304f32a7aecc5b143504e378c532d", "text": "import { describe, expect, test } from 'vitest'\nimport { browserLogs, isBuild, page } from '~utils'\n\ntest('should have no 404s', () => {\n browserLogs.forEach((msg) => {\n expect(msg).not.toMatch('404')\n })\n})\n\ndescribe.runIf(isBuild)('build', () => {\n test('dynamic import', async () => {\n await page.waitForSelector('#done')\n expect(await page.textContent('#done')).toBe('ran js')\n })\n\n test('dynamic import with comments', async () => {\n await page.click('#hello .load')\n await page.waitForSelector('#hello output')\n\n const html = await page.content()\n expect(html).toMatch(\n /link rel=\"modulepreload\".*?href=\".*?\\/assets\\/hello-[-\\w]{8}\\.js\"/,\n )\n expect(html).toMatch(\n /link rel=\"stylesheet\".*?href=\".*?\\/assets\\/hello-[-\\w]{8}\\.css\"/,\n )\n })\n})", "messages": null, "tools": null} {"id": "034ec8c4eedc73c0", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "include/nlohmann/detail/macro_unscope.hpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 1374, "sha256": "196107a14e4a3f62caa88187c7cb23dc35b387fba849cd4c16b3d4e5b2e9ebfe", "text": "// __ _____ _____ _____\n// __| | __| | | | JSON for Modern C++\n// | | |__ | | | | | | version 3.12.0\n// |_____|_____|_____|_|___| https://github.com/nlohmann/json\n//\n// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann \n// SPDX-License-Identifier: MIT\n\n#pragma once\n\n// restore clang diagnostic settings\n#if defined(__clang__)\n #pragma clang diagnostic pop\n#endif\n\n// clean up\n#undef JSON_ASSERT\n#undef JSON_INTERNAL_CATCH\n#undef JSON_THROW\n#undef JSON_PRIVATE_UNLESS_TESTED\n#undef NLOHMANN_BASIC_JSON_TPL_DECLARATION\n#undef NLOHMANN_BASIC_JSON_TPL\n#undef JSON_EXPLICIT\n#undef NLOHMANN_CAN_CALL_STD_FUNC_IMPL\n#undef JSON_INLINE_VARIABLE\n#undef JSON_NO_UNIQUE_ADDRESS\n#undef JSON_DISABLE_ENUM_SERIALIZATION\n#undef JSON_USE_GLOBAL_UDLS\n#undef JSON_BRACE_INIT_COPY_SEMANTICS\n\n#ifndef JSON_TEST_KEEP_MACROS\n #undef JSON_CATCH\n #undef JSON_TRY\n #undef JSON_HAS_CPP_11\n #undef JSON_HAS_CPP_14\n #undef JSON_HAS_CPP_17\n #undef JSON_HAS_CPP_20\n #undef JSON_HAS_CPP_23\n #undef JSON_HAS_CPP_26\n #undef JSON_HAS_FILESYSTEM\n #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM\n #undef JSON_HAS_THREE_WAY_COMPARISON\n #undef JSON_HAS_RANGES\n #undef JSON_HAS_STD_FORMAT\n #undef JSON_HAS_STATIC_RTTI\n #undef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON\n#endif\n\n#include ", "messages": null, "tools": null} {"id": "035a6fbf7bea973a", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/api/basic_json/is_number_float.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 1049, "sha256": "681a71a3e6c1b224b7cb8b020f98fc5b411a1a50ef18f7e1df7aeb85d8730446", "text": "# nlohmann::basic_json::is_number_float\n\n```cpp\nconstexpr bool is_number_float() const noexcept;\n```\n\nThis function returns `#!cpp true` if and only if the JSON value is a floating-point number. This excludes signed and\nunsigned integer values.\n \n## Return value\n\n`#!cpp true` if type is a floating-point number, `#!cpp false` otherwise.\n\n## Exception safety\n\nNo-throw guarantee: this member function never throws exceptions.\n\n## Complexity\n\nConstant.\n\n## Examples\n\n??? example\n\n The following code exemplifies `is_number_float()` for all JSON types.\n \n ```cpp\n --8<-- \"examples/is_number_float.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/is_number_float.output\"\n ```\n\n## See also\n\n- [is_number()](is_number.md) check if the value is a number\n- [is_number_integer()](is_number_integer.md) check if the value is an integer or unsigned integer number\n- [is_number_unsigned()](is_number_unsigned.md) check if the value is an unsigned integer number\n\n## Version history\n\n- Added in version 1.0.0.", "messages": null, "tools": null} {"id": "03939123dcd4bc2f", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/node/assetSource.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 4675, "sha256": "6bdc9ffada6423f3d58ba9260c86d4e2b6d6668f11facc6e91bbbe50b087f326", "text": "import type { DefaultTreeAdapterMap, Token } from 'parse5'\n\n/**\n * Defines which attributes of an HTML element should be treated as asset sources.\n * Used in `html.additionalAssetSources` configuration.\n */\nexport interface HtmlAssetSource {\n /**\n * Attributes that contain a single asset URL.\n * @example ['src', 'data-src-dark']\n */\n srcAttributes?: string[]\n /**\n * Attributes that contain srcset-format URLs.\n * @example ['srcset', 'imagesrcset']\n */\n srcsetAttributes?: string[]\n /**\n * Called before handling an attribute to determine if it should be processed.\n */\n filter?: (data: HtmlAssetSourceFilterData) => boolean\n}\n\ninterface HtmlAssetSourceFilterData {\n key: string\n value: string\n attributes: Record\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta/name\n// https://wiki.whatwg.org/wiki/MetaExtensions\nconst ALLOWED_META_NAME = [\n 'msapplication-tileimage',\n 'msapplication-square70x70logo',\n 'msapplication-square150x150logo',\n 'msapplication-wide310x150logo',\n 'msapplication-square310x310logo',\n 'msapplication-config',\n 'twitter:image',\n]\n\n// https://ogp.me\nconst ALLOWED_META_PROPERTY = [\n 'og:image',\n 'og:image:url',\n 'og:image:secure_url',\n 'og:audio',\n 'og:audio:secure_url',\n 'og:video',\n 'og:video:secure_url',\n]\n\nconst DEFAULT_HTML_ASSET_SOURCES: Record = {\n audio: {\n srcAttributes: ['src'],\n },\n embed: {\n srcAttributes: ['src'],\n },\n img: {\n srcAttributes: ['src'],\n srcsetAttributes: ['srcset'],\n },\n image: {\n srcAttributes: ['href', 'xlink:href'],\n },\n input: {\n srcAttributes: ['src'],\n },\n link: {\n srcAttributes: ['href'],\n srcsetAttributes: ['imagesrcset'],\n },\n object: {\n srcAttributes: ['data'],\n },\n source: {\n srcAttributes: ['src'],\n srcsetAttributes: ['srcset'],\n },\n track: {\n srcAttributes: ['src'],\n },\n use: {\n srcAttributes: ['href', 'xlink:href'],\n },\n video: {\n srcAttributes: ['src', 'poster'],\n },\n meta: {\n srcAttributes: ['content'],\n filter({ attributes }) {\n if (\n attributes.name &&\n ALLOWED_META_NAME.includes(attributes.name.trim().toLowerCase())\n ) {\n return true\n }\n\n if (\n attributes.property &&\n ALLOWED_META_PROPERTY.includes(attributes.property.trim().toLowerCase())\n ) {\n return true\n }\n\n return false\n },\n },\n}\n\ninterface HtmlAssetAttribute {\n type: 'src' | 'srcset' | 'remove'\n key: string\n value: string\n attributes: Record\n location: Token.Location\n}\n\n/**\n * Given a HTML node, find all attributes that references an asset to be processed\n */\nexport function getNodeAssetAttributes(\n node: DefaultTreeAdapterMap['element'],\n additionalAssetSources?: Record,\n): HtmlAssetAttribute[] {\n const defaults = DEFAULT_HTML_ASSET_SOURCES[node.nodeName]\n const additional = additionalAssetSources?.[node.nodeName]\n\n if (!defaults && !additional) return []\n\n const attributes: Record = {}\n for (const attr of node.attrs) {\n attributes[getAttrKey(attr)] = attr.value\n }\n\n // If the node has a `vite-ignore` attribute, remove the attribute and early out\n // to skip processing any attributes\n if ('vite-ignore' in attributes) {\n return [\n {\n type: 'remove',\n key: 'vite-ignore',\n value: '',\n attributes,\n location: node.sourceCodeLocation!.attrs!['vite-ignore'],\n },\n ]\n }\n\n const actions: HtmlAssetAttribute[] = []\n function handleAttributeKey(\n key: string,\n type: 'src' | 'srcset',\n filter?: (data: HtmlAssetSourceFilterData) => boolean,\n ) {\n const value = attributes[key]\n if (!value) return\n if (filter && !filter({ key, value, attributes })) return\n const location = node.sourceCodeLocation!.attrs![key]\n actions.push({ type, key, value, attributes, location })\n }\n\n // Run matching for default asset sources\n if (defaults) {\n defaults.srcAttributes?.forEach((key) =>\n handleAttributeKey(key, 'src', defaults.filter),\n )\n defaults.srcsetAttributes?.forEach((key) =>\n handleAttributeKey(key, 'srcset', defaults.filter),\n )\n }\n\n // Run matching for additional asset sources\n if (additional) {\n additional.srcAttributes?.forEach((key) =>\n handleAttributeKey(key, 'src', additional.filter),\n )\n additional.srcsetAttributes?.forEach((key) =>\n handleAttributeKey(key, 'srcset', additional.filter),\n )\n }\n\n return actions\n}\n\nfunction getAttrKey(attr: Token.Attribute): string {\n return attr.prefix === undefined ? attr.name : `${attr.prefix}:${attr.name}`\n}", "messages": null, "tools": null} {"id": "03aae8fea0f41124", "category": "code", "domain": "code", "source": "ripgrep", "license": "MIT OR Unlicense", "license_url": "https://spdx.org/licenses/MIT.html", "path": "crates/searcher/src/line_buffer.rs", "lang": "rust", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/BurntSushi/ripgrep", "commit": "3fce3b5bb0236da2df6d99672afb8a719642eca7", "collector": "tools/harvest.py"}, "chars": 35187, "sha256": "8ff22ddfa1b6da2a5f64f36f1117372980b50c674baeaece34058be0b7d019d5", "text": "use std::io;\n\nuse bstr::ByteSlice;\n\n/// The default buffer capacity that we use for the line buffer.\npub(crate) const DEFAULT_BUFFER_CAPACITY: usize = 64 * (1 << 10); // 64 KB\n\n/// The behavior of a searcher in the face of long lines and big contexts.\n///\n/// When searching data incrementally using a fixed size buffer, this controls\n/// the amount of *additional* memory to allocate beyond the size of the buffer\n/// to accommodate lines (which may include the lines in a context window, when\n/// enabled) that do not fit in the buffer.\n///\n/// The default is to eagerly allocate without a limit.\n#[derive(Clone, Copy, Debug)]\npub(crate) enum BufferAllocation {\n /// Attempt to expand the size of the buffer until either at least the next\n /// line fits into memory or until all available memory is exhausted.\n ///\n /// This is the default.\n Eager,\n /// Limit the amount of additional memory allocated to the given size. If\n /// a line is found that requires more memory than is allowed here, then\n /// stop reading and return an error.\n Error(usize),\n}\n\nimpl Default for BufferAllocation {\n fn default() -> BufferAllocation {\n BufferAllocation::Eager\n }\n}\n\n/// Create a new error to be used when a configured allocation limit has been\n/// reached.\npub(crate) fn alloc_error(limit: usize) -> io::Error {\n let msg = format!(\"configured allocation limit ({}) exceeded\", limit);\n io::Error::new(io::ErrorKind::Other, msg)\n}\n\n/// The behavior of binary detection in the line buffer.\n///\n/// Binary detection is the process of _heuristically_ identifying whether a\n/// given chunk of data is binary or not, and then taking an action based on\n/// the result of that heuristic. The motivation behind detecting binary data\n/// is that binary data often indicates data that is undesirable to search\n/// using textual patterns. Of course, there are many cases in which this isn't\n/// true, which is why binary detection is disabled by default.\n#[derive(Clone, Copy, Debug, Eq, PartialEq)]\npub(crate) enum BinaryDetection {\n /// No binary detection is performed. Data reported by the line buffer may\n /// contain arbitrary bytes.\n None,\n /// The given byte is searched in all contents read by the line buffer. If\n /// it occurs, then the data is considered binary and the line buffer acts\n /// as if it reached EOF. The line buffer guarantees that this byte will\n /// never be observable by callers.\n Quit(u8),\n /// The given byte is searched in all contents read by the line buffer. If\n /// it occurs, then it is replaced by the line terminator. The line buffer\n /// guarantees that this byte will never be observable by callers.\n Convert(u8),\n}\n\nimpl Default for BinaryDetection {\n fn default() -> BinaryDetection {\n BinaryDetection::None\n }\n}\n\nimpl BinaryDetection {\n /// Returns true if and only if the detection heuristic demands that\n /// the line buffer stop read data once binary data is observed.\n fn is_quit(&self) -> bool {\n match *self {\n BinaryDetection::Quit(_) => true,\n _ => false,\n }\n }\n}\n\n/// The configuration of a buffer. This contains options that are fixed once\n/// a buffer has been constructed.\n#[derive(Clone, Copy, Debug)]\nstruct Config {\n /// The number of bytes to attempt to read at a time.\n capacity: usize,\n /// The line terminator.\n lineterm: u8,\n /// The behavior for handling long lines.\n buffer_alloc: BufferAllocation,\n /// When set, the presence of the given byte indicates binary content.\n binary: BinaryDetection,\n}\n\nimpl Default for Config {\n fn default() -> Config {\n Config {\n capacity: DEFAULT_BUFFER_CAPACITY,\n lineterm: b'\\n',\n buffer_alloc: BufferAllocation::default(),\n binary: BinaryDetection::default(),\n }\n }\n}\n\n/// A builder for constructing line buffers.\n#[derive(Clone, Debug, Default)]\npub(crate) struct LineBufferBuilder {\n config: Config,\n}\n\nimpl LineBufferBuilder {\n /// Create a new builder for a buffer.\n pub(crate) fn new() -> LineBufferBuilder {\n LineBufferBuilder { config: Config::default() }\n }\n\n /// Create a new line buffer from this builder's configuration.\n pub(crate) fn build(&self) -> LineBuffer {\n LineBuffer {\n config: self.config,\n buf: vec![0; self.config.capacity],\n pos: 0,\n last_lineterm: 0,\n end: 0,\n absolute_byte_offset: 0,\n binary_byte_offset: None,\n }\n }\n\n /// Set the default capacity to use for a buffer.\n ///\n /// In general, the capacity of a buffer corresponds to the amount of data\n /// to hold in memory, and the size of the reads to make to the underlying\n /// reader.\n ///\n /// This is set to a reasonable default and probably shouldn't be changed\n /// unless there's a specific reason to do so.\n pub(crate) fn capacity(\n &mut self,\n capacity: usize,\n ) -> &mut LineBufferBuilder {\n self.config.capacity = capacity;\n self\n }\n\n /// Set the line terminator for the buffer.\n ///\n /// Every buffer has a line terminator, and this line terminator is used\n /// to determine how to roll the buffer forward. For example, when a read\n /// to the buffer's underlying reader occurs, the end of the data that is\n /// read is likely to correspond to an incomplete line. As a line buffer,\n /// callers should not access this data since it is incomplete. The line\n /// terminator is how the line buffer determines the part of the read that\n /// is incomplete.\n ///\n /// By default, this is set to `b'\\n'`.\n pub(crate) fn line_terminator(\n &mut self,\n lineterm: u8,\n ) -> &mut LineBufferBuilder {\n self.config.lineterm = lineterm;\n self\n }\n\n /// Set the maximum amount of additional memory to allocate for long lines.\n ///\n /// In order to enable line oriented search, a fundamental requirement is\n /// that, at a minimum, each line must be able to fit into memory. This\n /// setting controls how big that line is allowed to be. By default, this\n /// is set to `BufferAllocation::Eager`, which means a line buffer will\n /// attempt to allocate as much memory as possible to fit a line, and will\n /// only be limited by available memory.\n ///\n /// Note that this setting only applies to the amount of *additional*\n /// memory to allocate, beyond the capacity of the buffer. That means that\n /// a value of `0` is sensible, and in particular, will guarantee that a\n /// line buffer will never allocate additional memory beyond its initial\n /// capacity.\n pub(crate) fn buffer_alloc(\n &mut self,\n behavior: BufferAllocation,\n ) -> &mut LineBufferBuilder {\n self.config.buffer_alloc = behavior;\n self\n }\n\n /// Whether to enable binary detection or not. Depending on the setting,\n /// this can either cause the line buffer to report EOF early or it can\n /// cause the line buffer to clean the data.\n ///\n /// By default, this is disabled. In general, binary detection should be\n /// viewed as an imperfect heuristic.\n pub(crate) fn binary_detection(\n &mut self,\n detection: BinaryDetection,\n ) -> &mut LineBufferBuilder {\n self.config.binary = detection;\n self\n }\n}\n\n/// A line buffer reader efficiently reads a line oriented buffer from an\n/// arbitrary reader.\n#[derive(Debug)]\npub(crate) struct LineBufferReader<'b, R> {\n rdr: R,\n line_buffer: &'b mut LineBuffer,\n}\n\nimpl<'b, R: io::Read> LineBufferReader<'b, R> {\n /// Create a new buffered reader that reads from `rdr` and uses the given\n /// `line_buffer` as an intermediate buffer.\n ///\n /// This does not change the binary detection behavior of the given line\n /// buffer.\n pub(crate) fn new(\n rdr: R,\n line_buffer: &'b mut LineBuffer,\n ) -> LineBufferReader<'b, R> {\n line_buffer.clear();\n LineBufferReader { rdr, line_buffer }\n }\n\n /// The absolute byte offset which corresponds to the starting offsets\n /// of the data returned by `buffer` relative to the beginning of the\n /// underlying reader's contents. As such, this offset does not generally\n /// correspond to an offset in memory. It is typically used for reporting\n /// purposes. It can also be used for counting the number of bytes that\n /// have been searched.\n pub(crate) fn absolute_byte_offset(&self) -> u64 {\n self.line_buffer.absolute_byte_offset()\n }\n\n /// If binary data was detected, then this returns the absolute byte offset\n /// at which binary data was initially found.\n pub(crate) fn binary_byte_offset(&self) -> Option {\n self.line_buffer.binary_byte_offset()\n }\n\n /// Fill the contents of this buffer by discarding the part of the buffer\n /// that has been consumed. The free space created by discarding the\n /// consumed part of the buffer is then filled with new data from the\n /// reader.\n ///\n /// If EOF is reached, then `false` is returned. Otherwise, `true` is\n /// returned. (Note that if this line buffer's binary detection is set to\n /// `Quit`, then the presence of binary data will cause this buffer to\n /// behave as if it had seen EOF at the first occurrence of binary data.)\n ///\n /// This forwards any errors returned by the underlying reader, and will\n /// also return an error if the buffer must be expanded past its allocation\n /// limit, as governed by the buffer allocation strategy.\n pub(crate) fn fill(&mut self) -> Result {\n self.line_buffer.fill(&mut self.rdr)\n }\n\n /// Return the contents of this buffer.\n pub(crate) fn buffer(&self) -> &[u8] {\n self.line_buffer.buffer()\n }\n\n /// Return the buffer as a BStr, used for convenient equality checking\n /// in tests only.\n #[cfg(test)]\n fn bstr(&self) -> &bstr::BStr {\n self.buffer().as_bstr()\n }\n\n /// Consume the number of bytes provided. This must be less than or equal\n /// to the number of bytes returned by `buffer`.\n pub(crate) fn consume(&mut self, amt: usize) {\n self.line_buffer.consume(amt);\n }\n\n /// Consumes the remainder of the buffer. Subsequent calls to `buffer` are\n /// guaranteed to return an empty slice until the buffer is refilled.\n ///\n /// This is a convenience function for `consume(buffer.len())`.\n #[cfg(test)]\n fn consume_all(&mut self) {\n self.line_buffer.consume_all();\n }\n}\n\n/// A line buffer manages a (typically fixed) buffer for holding lines.\n///\n/// Callers should create line buffers sparingly and reuse them when possible.\n/// Line buffers cannot be used directly, but instead must be used via the\n/// LineBufferReader.\n#[derive(Clone, Debug)]\npub(crate) struct LineBuffer {\n /// The configuration of this buffer.\n config: Config,\n /// The primary buffer with which to hold data.\n buf: Vec,\n /// The current position of this buffer. This is always a valid sliceable\n /// index into `buf`, and its maximum value is the length of `buf`.\n pos: usize,\n /// The end position of searchable content in this buffer. This is either\n /// set to just after the final line terminator in the buffer, or to just\n /// after the end of the last byte emitted by the reader when the reader\n /// has been exhausted.\n last_lineterm: usize,\n /// The end position of the buffer. This is always greater than or equal to\n /// last_lineterm. The bytes between last_lineterm and end, if any, always\n /// correspond to a partial line.\n end: usize,\n /// The absolute byte offset corresponding to `pos`. This is most typically\n /// not a valid index into addressable memory, but rather, an offset that\n /// is relative to all data that passes through a line buffer (since\n /// construction or since the last time `clear` was called).\n ///\n /// When the line buffer reaches EOF, this is set to the position just\n /// after the last byte read from the underlying reader. That is, it\n /// becomes the total count of bytes that have been read.\n absolute_byte_offset: u64,\n /// If binary data was found, this records the absolute byte offset at\n /// which it was first detected.\n binary_byte_offset: Option,\n}\n\nimpl LineBuffer {\n /// Set the binary detection method used on this line buffer.\n ///\n /// This permits dynamically changing the binary detection strategy on\n /// an existing line buffer without needing to create a new one.\n pub(crate) fn set_binary_detection(&mut self, binary: BinaryDetection) {\n self.config.binary = binary;\n }\n\n /// Reset this buffer, such that it can be used with a new reader.\n fn clear(&mut self) {\n self.pos = 0;\n self.last_lineterm = 0;\n self.end = 0;\n self.absolute_byte_offset = 0;\n self.binary_byte_offset = None;\n }\n\n /// The absolute byte offset which corresponds to the starting offsets\n /// of the data returned by `buffer` relative to the beginning of the\n /// reader's contents. As such, this offset does not generally correspond\n /// to an offset in memory. It is typically used for reporting purposes,\n /// particularly in error messages.\n ///\n /// This is reset to `0` when `clear` is called.\n fn absolute_byte_offset(&self) -> u64 {\n self.absolute_byte_offset\n }\n\n /// If binary data was detected, then this returns the absolute byte offset\n /// at which binary data was initially found.\n fn binary_byte_offset(&self) -> Option {\n self.binary_byte_offset\n }\n\n /// Return the contents of this buffer.\n fn buffer(&self) -> &[u8] {\n &self.buf[self.pos..self.last_lineterm]\n }\n\n /// Return the contents of the free space beyond the end of the buffer as\n /// a mutable slice.\n fn free_buffer(&mut self) -> &mut [u8] {\n &mut self.buf[self.end..]\n }\n\n /// Consume the number of bytes provided. This must be less than or equal\n /// to the number of bytes returned by `buffer`.\n fn consume(&mut self, amt: usize) {\n assert!(amt <= self.buffer().len());\n self.pos += amt;\n self.absolute_byte_offset += amt as u64;\n }\n\n /// Consumes the remainder of the buffer. Subsequent calls to `buffer` are\n /// guaranteed to return an empty slice until the buffer is refilled.\n ///\n /// This is a convenience function for `consume(buffer.len())`.\n #[cfg(test)]\n fn consume_all(&mut self) {\n let amt = self.buffer().len();\n self.consume(amt);\n }\n\n /// Fill the contents of this buffer by discarding the part of the buffer\n /// that has been consumed. The free space created by discarding the\n /// consumed part of the buffer is then filled with new data from the given\n /// reader.\n ///\n /// Callers should provide the same reader to this line buffer in\n /// subsequent calls to fill. A different reader can only be used\n /// immediately following a call to `clear`.\n ///\n /// If EOF is reached, then `false` is returned. Otherwise, `true` is\n /// returned. (Note that if this line buffer's binary detection is set to\n /// `Quit`, then the presence of binary data will cause this buffer to\n /// behave as if it had seen EOF.)\n ///\n /// This forwards any errors returned by `rdr`, and will also return an\n /// error if the buffer must be expanded past its allocation limit, as\n /// governed by the buffer allocation strategy.\n fn fill(&mut self, mut rdr: R) -> Result {\n // If the binary detection heuristic tells us to quit once binary data\n // has been observed, then we no longer read new data and reach EOF\n // once the current buffer has been consumed.\n if self.config.binary.is_quit() && self.binary_byte_offset.is_some() {\n return Ok(!self.buffer().is_empty());\n }\n\n self.roll();\n assert_eq!(self.pos, 0);\n loop {\n self.ensure_capacity()?;\n let readlen = rdr.read(self.free_buffer().as_bytes_mut())?;\n if readlen == 0 {\n // We're only done reading for good once the caller has\n // consumed everything.\n self.last_lineterm = self.end;\n return Ok(!self.buffer().is_empty());\n }\n\n // Get a mutable view into the bytes we've just read. These are\n // the bytes that we do binary detection on, and also the bytes we\n // search to find the last line terminator. We need a mutable slice\n // in the case of binary conversion.\n let oldend = self.end;\n self.end += readlen;\n let newbytes = &mut self.buf[oldend..self.end];\n\n // Binary detection.\n match self.config.binary {\n BinaryDetection::None => {} // nothing to do\n BinaryDetection::Quit(byte) => {\n if let Some(i) = newbytes.find_byte(byte) {\n self.end = oldend + i;\n self.last_lineterm = self.end;\n self.binary_byte_offset =\n Some(self.absolute_byte_offset + self.end as u64);\n // If the first byte in our buffer is a binary byte,\n // then our buffer is empty and we should report as\n // such to the caller.\n return Ok(self.pos < self.end);\n }\n }\n BinaryDetection::Convert(byte) => {\n if let Some(i) =\n replace_bytes(newbytes, byte, self.config.lineterm)\n {\n // Record only the first binary offset.\n if self.binary_byte_offset.is_none() {\n self.binary_byte_offset = Some(\n self.absolute_byte_offset\n + (oldend + i) as u64,\n );\n }\n }\n }\n }\n\n // Update our `last_lineterm` positions if we read one.\n if let Some(i) = newbytes.rfind_byte(self.config.lineterm) {\n self.last_lineterm = oldend + i + 1;\n return Ok(true);\n }\n // At this point, if we couldn't find a line terminator, then we\n // don't have a complete line. Therefore, we try to read more!\n }\n }\n\n /// Roll the unconsumed parts of the buffer to the front.\n ///\n /// This operation is idempotent.\n ///\n /// After rolling, `last_lineterm` and `end` point to the same location,\n /// and `pos` is always set to `0`.\n fn roll(&mut self) {\n if self.pos == self.end {\n self.pos = 0;\n self.last_lineterm = 0;\n self.end = 0;\n return;\n }\n\n let roll_len = self.end - self.pos;\n self.buf.copy_within(self.pos..self.end, 0);\n self.pos = 0;\n self.last_lineterm = roll_len;\n self.end = roll_len;\n }\n\n /// Ensures that the internal buffer has a non-zero amount of free space\n /// in which to read more data. If there is no free space, then more is\n /// allocated. If the allocation must exceed the configured limit, then\n /// this returns an error.\n fn ensure_capacity(&mut self) -> Result<(), io::Error> {\n if !self.free_buffer().is_empty() {\n return Ok(());\n }\n // `len` is used for computing the next allocation size. The capacity\n // is permitted to start at `0`, so we make sure it's at least `1`.\n let len = std::cmp::max(1, self.buf.len());\n let additional = match self.config.buffer_alloc {\n BufferAllocation::Eager => len * 2,\n BufferAllocation::Error(limit) => {\n let used = self.buf.len() - self.config.capacity;\n let n = std::cmp::min(len * 2, limit - used);\n if n == 0 {\n return Err(alloc_error(self.config.capacity + limit));\n }\n n\n }\n };\n assert!(additional > 0);\n let newlen = self.buf.len() + additional;\n self.buf.resize(newlen, 0);\n assert!(!self.free_buffer().is_empty());\n Ok(())\n }\n}\n\n/// Replaces `src` with `replacement` in bytes, and return the offset of the\n/// first replacement, if one exists.\nfn replace_bytes(\n mut bytes: &mut [u8],\n src: u8,\n replacement: u8,\n) -> Option {\n if src == replacement {\n return None;\n }\n let first_pos = bytes.find_byte(src)?;\n bytes[first_pos] = replacement;\n bytes = &mut bytes[first_pos + 1..];\n while let Some(i) = bytes.find_byte(src) {\n bytes[i] = replacement;\n bytes = &mut bytes[i + 1..];\n\n // To search for adjacent `src` bytes we use a different strategy.\n // Since binary data tends to have long runs of NUL terminators,\n // it is faster to compare one-byte-at-a-time than to stop and start\n // memchr (through `find_byte`) for every byte in a sequence.\n while bytes.get(0) == Some(&src) {\n bytes[0] = replacement;\n bytes = &mut bytes[1..];\n }\n }\n Some(first_pos)\n}\n\n#[cfg(test)]\nmod tests {\n use bstr::ByteVec;\n\n use super::*;\n\n const SHERLOCK: &'static str = \"\\\nFor the Doctor Watsons of this world, as opposed to the Sherlock\nHolmeses, success in the province of detective work must always\nbe, to a very large extent, the result of luck. Sherlock Holmes\ncan extract a clew from a wisp of straw or a flake of cigar ash;\nbut Doctor Watson has to have it taken out for him and dusted,\nand exhibited clearly, with a label attached.\\\n\";\n\n fn s(slice: &str) -> String {\n slice.to_string()\n }\n\n fn replace_str(\n slice: &str,\n src: u8,\n replacement: u8,\n ) -> (String, Option) {\n let mut dst = Vec::from(slice);\n let result = replace_bytes(&mut dst, src, replacement);\n (dst.into_string().unwrap(), result)\n }\n\n #[test]\n fn replace() {\n assert_eq!(replace_str(\"\", b'b', b'z'), (s(\"\"), None));\n assert_eq!(replace_str(\"a\", b'a', b'a'), (s(\"a\"), None));\n assert_eq!(replace_str(\"a\", b'b', b'z'), (s(\"a\"), None));\n assert_eq!(replace_str(\"abc\", b'b', b'z'), (s(\"azc\"), Some(1)));\n assert_eq!(replace_str(\"abb\", b'b', b'z'), (s(\"azz\"), Some(1)));\n assert_eq!(replace_str(\"aba\", b'a', b'z'), (s(\"zbz\"), Some(0)));\n assert_eq!(replace_str(\"bbb\", b'b', b'z'), (s(\"zzz\"), Some(0)));\n assert_eq!(replace_str(\"bac\", b'b', b'z'), (s(\"zac\"), Some(0)));\n }\n\n #[test]\n fn buffer_basics1() {\n let bytes = \"homer\\nlisa\\nmaggie\";\n let mut linebuf = LineBufferBuilder::new().build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.buffer().is_empty());\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\nlisa\\n\");\n assert_eq!(rdr.absolute_byte_offset(), 0);\n rdr.consume(5);\n assert_eq!(rdr.absolute_byte_offset(), 5);\n rdr.consume_all();\n assert_eq!(rdr.absolute_byte_offset(), 11);\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"maggie\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), None);\n }\n\n #[test]\n fn buffer_basics2() {\n let bytes = \"homer\\nlisa\\nmaggie\\n\";\n let mut linebuf = LineBufferBuilder::new().build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\nlisa\\nmaggie\\n\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), None);\n }\n\n #[test]\n fn buffer_basics3() {\n let bytes = \"\\n\";\n let mut linebuf = LineBufferBuilder::new().build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"\\n\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), None);\n }\n\n #[test]\n fn buffer_basics4() {\n let bytes = \"\\n\\n\";\n let mut linebuf = LineBufferBuilder::new().build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"\\n\\n\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), None);\n }\n\n #[test]\n fn buffer_empty() {\n let bytes = \"\";\n let mut linebuf = LineBufferBuilder::new().build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), None);\n }\n\n #[test]\n fn buffer_zero_capacity() {\n let bytes = \"homer\\nlisa\\nmaggie\";\n let mut linebuf = LineBufferBuilder::new().capacity(0).build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n while rdr.fill().unwrap() {\n rdr.consume_all();\n }\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), None);\n }\n\n #[test]\n fn buffer_small_capacity() {\n let bytes = \"homer\\nlisa\\nmaggie\";\n let mut linebuf = LineBufferBuilder::new().capacity(1).build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n let mut got = vec![];\n while rdr.fill().unwrap() {\n got.push_str(rdr.buffer());\n rdr.consume_all();\n }\n assert_eq!(bytes, got.as_bstr());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), None);\n }\n\n #[test]\n fn buffer_limited_capacity1() {\n let bytes = \"homer\\nlisa\\nmaggie\";\n let mut linebuf = LineBufferBuilder::new()\n .capacity(1)\n .buffer_alloc(BufferAllocation::Error(5))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\n\");\n rdr.consume_all();\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"lisa\\n\");\n rdr.consume_all();\n\n // This returns an error because while we have just enough room to\n // store maggie in the buffer, we *don't* have enough room to read one\n // more byte, so we don't know whether we're at EOF or not, and\n // therefore must give up.\n assert!(rdr.fill().is_err());\n\n // We can mush on though!\n assert_eq!(rdr.bstr(), \"m\");\n rdr.consume_all();\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"aggie\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n }\n\n #[test]\n fn buffer_limited_capacity2() {\n let bytes = \"homer\\nlisa\\nmaggie\";\n let mut linebuf = LineBufferBuilder::new()\n .capacity(1)\n .buffer_alloc(BufferAllocation::Error(6))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\n\");\n rdr.consume_all();\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"lisa\\n\");\n rdr.consume_all();\n\n // We have just enough space.\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"maggie\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n }\n\n #[test]\n fn buffer_limited_capacity3() {\n let bytes = \"homer\\nlisa\\nmaggie\";\n let mut linebuf = LineBufferBuilder::new()\n .capacity(1)\n .buffer_alloc(BufferAllocation::Error(0))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.fill().is_err());\n assert_eq!(rdr.bstr(), \"\");\n }\n\n #[test]\n fn buffer_binary_none() {\n let bytes = \"homer\\nli\\x00sa\\nmaggie\\n\";\n let mut linebuf = LineBufferBuilder::new().build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.buffer().is_empty());\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\nli\\x00sa\\nmaggie\\n\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), None);\n }\n\n #[test]\n fn buffer_binary_quit1() {\n let bytes = \"homer\\nli\\x00sa\\nmaggie\\n\";\n let mut linebuf = LineBufferBuilder::new()\n .binary_detection(BinaryDetection::Quit(b'\\x00'))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.buffer().is_empty());\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\nli\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), 8);\n assert_eq!(rdr.binary_byte_offset(), Some(8));\n }\n\n #[test]\n fn buffer_binary_quit2() {\n let bytes = \"\\x00homer\\nlisa\\nmaggie\\n\";\n let mut linebuf = LineBufferBuilder::new()\n .binary_detection(BinaryDetection::Quit(b'\\x00'))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"\");\n assert_eq!(rdr.absolute_byte_offset(), 0);\n assert_eq!(rdr.binary_byte_offset(), Some(0));\n }\n\n #[test]\n fn buffer_binary_quit3() {\n let bytes = \"homer\\nlisa\\nmaggie\\n\\x00\";\n let mut linebuf = LineBufferBuilder::new()\n .binary_detection(BinaryDetection::Quit(b'\\x00'))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.buffer().is_empty());\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\nlisa\\nmaggie\\n\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64 - 1);\n assert_eq!(rdr.binary_byte_offset(), Some(bytes.len() as u64 - 1));\n }\n\n #[test]\n fn buffer_binary_quit4() {\n let bytes = \"homer\\nlisa\\nmaggie\\x00\\n\";\n let mut linebuf = LineBufferBuilder::new()\n .binary_detection(BinaryDetection::Quit(b'\\x00'))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.buffer().is_empty());\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\nlisa\\nmaggie\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64 - 2);\n assert_eq!(rdr.binary_byte_offset(), Some(bytes.len() as u64 - 2));\n }\n\n #[test]\n fn buffer_binary_quit5() {\n let mut linebuf = LineBufferBuilder::new()\n .binary_detection(BinaryDetection::Quit(b'u'))\n .build();\n let mut rdr = LineBufferReader::new(SHERLOCK.as_bytes(), &mut linebuf);\n\n assert!(rdr.buffer().is_empty());\n\n assert!(rdr.fill().unwrap());\n assert_eq!(\n rdr.bstr(),\n \"\\\nFor the Doctor Watsons of this world, as opposed to the Sherlock\nHolmeses, s\\\n\"\n );\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), 76);\n assert_eq!(rdr.binary_byte_offset(), Some(76));\n assert_eq!(SHERLOCK.as_bytes()[76], b'u');\n }\n\n #[test]\n fn buffer_binary_convert1() {\n let bytes = \"homer\\nli\\x00sa\\nmaggie\\n\";\n let mut linebuf = LineBufferBuilder::new()\n .binary_detection(BinaryDetection::Convert(b'\\x00'))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.buffer().is_empty());\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\nli\\nsa\\nmaggie\\n\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), Some(8));\n }\n\n #[test]\n fn buffer_binary_convert2() {\n let bytes = \"\\x00homer\\nlisa\\nmaggie\\n\";\n let mut linebuf = LineBufferBuilder::new()\n .binary_detection(BinaryDetection::Convert(b'\\x00'))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.buffer().is_empty());\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"\\nhomer\\nlisa\\nmaggie\\n\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), Some(0));\n }\n\n #[test]\n fn buffer_binary_convert3() {\n let bytes = \"homer\\nlisa\\nmaggie\\n\\x00\";\n let mut linebuf = LineBufferBuilder::new()\n .binary_detection(BinaryDetection::Convert(b'\\x00'))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.buffer().is_empty());\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\nlisa\\nmaggie\\n\\n\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), Some(bytes.len() as u64 - 1));\n }\n\n #[test]\n fn buffer_binary_convert4() {\n let bytes = \"homer\\nlisa\\nmaggie\\x00\\n\";\n let mut linebuf = LineBufferBuilder::new()\n .binary_detection(BinaryDetection::Convert(b'\\x00'))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.buffer().is_empty());\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\nlisa\\nmaggie\\n\\n\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), Some(bytes.len() as u64 - 2));\n }\n}", "messages": null, "tools": null} {"id": "041dcee8d42ca15f", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/resolve-tsconfig-paths/__tests__/resolve.spec.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 1622, "sha256": "b17739a7814806eddd9456c74b2ca87ccaeeee507667697dd74002e110974d09", "text": "import { expect, test } from 'vitest'\nimport { getColor, page } from '~utils'\n\ntest('import from .ts', async () => {\n await expect.poll(() => page.textContent('.ts')).toMatch('[success]')\n})\n\ntest('import from .js', async () => {\n await expect.poll(() => page.textContent('.js')).toMatch('[success]')\n})\n\ntest('import using # prefixed path', async () => {\n await expect.poll(() => page.textContent('.hash')).toMatch('[success]')\n})\n\ntest('fallback works', async () => {\n await expect.poll(() => page.textContent('.fallback')).toMatch('[success]')\n})\n\ntest('nested tsconfig.json & references / include works', async () => {\n await expect.poll(() => page.textContent('.nested-a')).toMatch('[success]')\n await expect.poll(() => page.textContent('.nested-b')).toMatch('[success]')\n})\n\ntest('import.meta.glob resolves tsconfig paths', async () => {\n await expect\n .poll(() => page.textContent('.glob-eager'))\n .toBe('[success] glob-a [success] glob-b')\n})\n\ntest('css @import resolves tsconfig paths', async () => {\n await expect.poll(() => getColor('.tsconfig-paths-css')).toBe('darkcyan')\n})\n\ntest('sass @use resolves tsconfig paths', async () => {\n await expect.poll(() => getColor('.tsconfig-paths-scss')).toBe('seagreen')\n})\n\n// `resolve.tsconfigPaths` is not supported inside `.less` files. The aliased\n// `@import (optional) '@/less-imported.less'` cannot resolve (even with\n// `**/*.less` in `include`), so it is skipped and the color stays `navy`.\ntest('less @import does not resolve tsconfig paths (unsupported)', async () => {\n await expect.poll(() => getColor('.tsconfig-paths-less')).toBe('navy')\n})", "messages": null, "tools": null} {"id": "04460825f0abc6c9", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/node/optimizer/resolve.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 6664, "sha256": "d3c376df546f0bb4298c3a4f7c2190d61d6478a40cc2a7ed60d14514026999a9", "text": "import path from 'node:path'\nimport picomatch from 'picomatch'\nimport { globSync } from 'tinyglobby'\nimport type { ResolvedConfig } from '../config'\nimport { escapeRegex, getNpmPackageName } from '../utils'\nimport { resolvePackageData } from '../packages'\nimport { slash } from '../../shared/utils'\nimport type { Environment } from '../environment'\nimport { createBackCompatIdResolver } from '../idResolver'\n\nexport function createOptimizeDepsIncludeResolver(\n environment: Environment,\n): (id: string) => Promise {\n const topLevelConfig = environment.getTopLevelConfig()\n const resolve = createBackCompatIdResolver(topLevelConfig, {\n asSrc: false,\n scan: true,\n packageCache: new Map(),\n })\n\n return async (id: string) => {\n const lastArrowIndex = id.lastIndexOf('>')\n if (lastArrowIndex === -1) {\n return await resolve(environment, id, undefined)\n }\n // split nested selected id by last '>', for example:\n // 'foo > bar > baz' => 'foo > bar' & 'baz'\n const nestedRoot = id.substring(0, lastArrowIndex).trim()\n const nestedPath = id.substring(lastArrowIndex + 1).trim()\n const basedir = nestedResolveBasedir(\n nestedRoot,\n topLevelConfig.root,\n topLevelConfig.resolve.preserveSymlinks,\n )\n return await resolve(\n environment,\n nestedPath,\n path.resolve(basedir, 'package.json'),\n )\n }\n}\n\n/**\n * Expand the glob syntax in `optimizeDeps.include` to proper import paths\n */\nexport function expandGlobIds(id: string, config: ResolvedConfig): string[] {\n const pkgName = getNpmPackageName(id)\n if (!pkgName) return []\n\n const pkgData = resolvePackageData(\n pkgName,\n config.root,\n config.resolve.preserveSymlinks,\n config.packageCache,\n )\n if (!pkgData) return []\n\n const pattern = '.' + id.slice(pkgName.length)\n const exports = pkgData.data.exports\n\n // if package has exports field, get all possible export paths and apply\n // glob on them with picomatch\n if (exports) {\n if (typeof exports === 'string' || Array.isArray(exports)) {\n return [pkgName]\n }\n\n const possibleExportPaths: string[] = []\n for (const key in exports) {\n if (key[0] === '.') {\n if (key.includes('*')) {\n // \"./glob/*\": {\n // \"browser\": \"./dist/glob/*-browser/*.js\", <-- get this one\n // \"default\": \"./dist/glob/*/*.js\"\n // }\n // NOTE: theoretically the \"default\" condition could map to a different\n // set of files, but that complicates the resolve logic, so we assume\n // all conditions map to the same set of files, and get the first one.\n const exportsValue = getFirstExportStringValue(exports[key])\n if (!exportsValue) continue\n\n // \"./dist/glob/*-browser/*.js\" => \"./dist/glob/**/*-browser/**/*.js\"\n // NOTE: in some cases, this could expand to consecutive /**/*/**/* etc\n // but it's fine since `tinyglobby` handles it the same.\n const exportValuePattern = exportsValue.replace(/\\*/g, '**/*')\n // \"./dist/glob/*-browser/*.js\" => /dist\\/glob\\/(.*)-browser\\/(.*)\\.js/\n const exportsValueGlobRe = new RegExp(\n exportsValue.split('*').map(escapeRegex).join('(.*)'),\n )\n\n possibleExportPaths.push(\n ...globSync(exportValuePattern, {\n cwd: pkgData.dir,\n expandDirectories: false,\n ignore: ['node_modules'],\n })\n .map((filePath) => {\n // `tinyglobby` returns paths as they are formatted by the underlying `fdir`.\n // Both `globSync(\"./some-dir/**/*\")` and `globSync(\"./**/*\")` result in\n // `\"some-dir/somefile\"` being returned, so we ensure the correct prefix manually.\n if (exportsValue.startsWith('./')) {\n filePath = './' + filePath\n }\n\n // \"./glob/*\": \"./dist/glob/*-browser/*.js\"\n // `filePath`: \"./dist/glob/foo-browser/foo.js\"\n // we need to revert the file path back to the export key by\n // matching value regex and replacing the capture groups to the key\n const matched = exportsValueGlobRe.exec(slash(filePath))\n // `matched`: [..., 'foo', 'foo']\n if (matched) {\n let allGlobSame = matched.length === 2\n // exports key can only have one *, so for >=2 matched groups,\n // make sure they have the same value\n if (!allGlobSame) {\n // assume true, if one group is different, set false and break\n allGlobSame = true\n for (let i = 2; i < matched.length; i++) {\n if (matched[i] !== matched[i - 1]) {\n allGlobSame = false\n break\n }\n }\n }\n if (allGlobSame) {\n return key.replace('*', matched[1]).slice(2)\n }\n }\n return ''\n })\n .filter(Boolean),\n )\n } else {\n // null export value means the subpath is intentionally private/blocked\n // https://nodejs.org/api/packages.html#subpath-patterns\n if (exports[key] == null) continue\n possibleExportPaths.push(key.slice(2))\n }\n }\n }\n\n const isMatch = picomatch(pattern)\n const matched = possibleExportPaths\n .filter((p) => isMatch(p))\n .map((match) => path.posix.join(pkgName, match))\n matched.unshift(pkgName)\n return matched\n } else {\n // for packages without exports, we can do a simple glob\n const matched = globSync(pattern, {\n cwd: pkgData.dir,\n expandDirectories: false,\n ignore: ['node_modules'],\n }).map((match) => path.posix.join(pkgName, slash(match)))\n matched.unshift(pkgName)\n return matched\n }\n}\n\nfunction getFirstExportStringValue(\n obj: string | string[] | Record,\n): string | undefined {\n if (typeof obj === 'string') {\n return obj\n } else if (Array.isArray(obj)) {\n return obj[0]\n } else {\n for (const key in obj) {\n return getFirstExportStringValue(obj[key])\n }\n }\n}\n\n/**\n * Continuously resolve the basedir of packages separated by '>'\n */\nfunction nestedResolveBasedir(\n id: string,\n basedir: string,\n preserveSymlinks = false,\n) {\n const pkgs = id.split('>').map((pkg) => pkg.trim())\n for (const pkg of pkgs) {\n basedir = resolvePackageData(pkg, basedir, preserveSymlinks)?.dir || basedir\n }\n return basedir\n}", "messages": null, "tools": null} {"id": "04bc29100f50699c", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/node/__tests_dts__/plugin.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 1552, "sha256": "68dabf1751c924fbfd2997e194902bb6801441e1d431b766266362ce6f3b4d61", "text": "/**\n * This is a development only file for testing types.\n */\nimport type { Plugin as RolldownPlugin } from 'rolldown'\nimport type { Equal, ExpectExtends, ExpectTrue } from '@type-challenges/utils'\nimport type { Plugin as RollupPlugin } from 'rollup'\nimport type { Plugin, PluginContextExtension, PluginOption } from '../plugin'\nimport type { ROLLUP_HOOKS } from '../constants'\nimport type {\n GetHookContextMap,\n NonNeverKeys,\n RollupPluginHooks,\n} from '../typeUtils'\n\ntype EnvironmentPluginHooksContext = GetHookContextMap\ntype EnvironmentPluginHooksContextMatched = {\n [K in keyof EnvironmentPluginHooksContext]: EnvironmentPluginHooksContext[K] extends PluginContextExtension\n ? never\n : false\n}\n\ntype HooksMissingExtension = NonNeverKeys\ntype HooksMissingInConstants = Exclude<\n RollupPluginHooks,\n (typeof ROLLUP_HOOKS)[number]\n>\n\nexport type cases = [\n // Ensure environment plugin hooks are superset of rollup plugin hooks\n ExpectTrue>,\n\n // Ensure all Rollup hooks have Vite's plugin context extension\n ExpectTrue>,\n\n // Ensure the `ROLLUP_HOOKS` constant is up-to-date\n ExpectTrue>,\n\n // Ensure all Vite plugins, Rolldown plugins, and Rollup plugins can be assigned to `plugins` option\n ExpectTrue>,\n ExpectTrue>,\n ExpectTrue>,\n]\n\nexport {}", "messages": null, "tools": null} {"id": "04d4436197789efe", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/shared/builtin.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 396, "sha256": "4da25871fae37da6b39d0aadd7ebf96f119b9468a680cfd2396ce2cf203b0622", "text": "export function createIsBuiltin(\n builtins: (string | RegExp)[],\n): (id: string) => boolean {\n const plainBuiltinsSet = new Set(\n builtins.filter((builtin) => typeof builtin === 'string'),\n )\n const regexBuiltins = builtins.filter(\n (builtin) => typeof builtin !== 'string',\n )\n\n return (id: string) =>\n plainBuiltinsSet.has(id) || regexBuiltins.some((regexp) => regexp.test(id))\n}", "messages": null, "tools": null} {"id": "054d1185cdc91922", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/thirdparty/Fuzzer/FuzzerRandom.h", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 1030, "sha256": "eb7bf791c69bb64b446b04fa61405d637fbd90cbcf583f8f9cc18650e3292006", "text": "//===- FuzzerRandom.h - Internal header for the Fuzzer ----------*- C++ -* ===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n// fuzzer::Random\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_FUZZER_RANDOM_H\n#define LLVM_FUZZER_RANDOM_H\n\n#include \n\nnamespace fuzzer {\nclass Random {\n public:\n Random(unsigned int seed) : R(seed) {}\n size_t Rand() { return R(); }\n size_t RandBool() { return Rand() % 2; }\n size_t operator()(size_t n) { return n ? Rand() % n : 0; }\n intptr_t operator()(intptr_t From, intptr_t To) {\n assert(From < To);\n intptr_t RangeSize = To - From + 1;\n return operator()(RangeSize) + From;\n }\n std::mt19937 &Get_mt19937() { return R; }\n private:\n std::mt19937 R;\n};\n\n} // namespace fuzzer\n\n#endif // LLVM_FUZZER_RANDOM_H", "messages": null, "tools": null} {"id": "06cfc58d23933e7d", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/README.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 1154, "sha256": "16e1b7f1349033515a069dccf4428de8b2528cbc1b838529649f9d61d3379f79", "text": "# Vite ⚡\n\n> Next Generation Frontend Tooling\n\n- 💡 Instant Server Start\n- ⚡️ Lightning Fast HMR\n- 🛠️ Rich Features\n- 📦 Optimized Build\n- 🔩 Universal Plugin Interface\n- 🔑 Fully Typed APIs\n\nVite (French word for \"quick\", pronounced [`/viːt/`](https://cdn.jsdelivr.net/gh/vitejs/vite@main/docs/public/vite.mp3), like \"veet\") is a build tool that aims to provide a faster and leaner development experience for modern web projects. It consists of two major parts:\n\n- A dev server that provides [rich feature enhancements](https://vite.dev/guide/features) over [native ES modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules), for example extremely fast [Hot Module Replacement (HMR)](https://vite.dev/guide/features#hot-module-replacement).\n\n- A build command that bundles your code with [Rolldown](https://rolldown.rs), pre-configured to output highly optimized static assets for production.\n\nIn addition, Vite is highly extensible via its [Plugin API](https://vite.dev/guide/api-plugin.html) and [JavaScript API](https://vite.dev/guide/api-javascript.html) with full typing support.\n\n[Read the Docs to Learn More](https://vite.dev).", "messages": null, "tools": null} {"id": "07186f048d4d8c47", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/thirdparty/Fuzzer/test/TimeoutEmptyTest.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 379, "sha256": "ca08abfd507d595a9b1607a650fd7a8bfb6024ed2b90baa1261a468bec99fb22", "text": "// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n\n// Simple test for a fuzzer. The fuzzer must find the empty string.\n#include \n#include \n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {\n static volatile int Zero = 0;\n if (!Size)\n while(!Zero)\n ;\n return 0;\n}", "messages": null, "tools": null} {"id": "07552c6913958d1c", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/css-sourcemap/__tests__/lib-entry/css-sourcemap-lib-entry.spec.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 283, "sha256": "72cc5f92f02b33a2785822670845c8e9bcd9282e4cb5dfa314e7b7404d147463", "text": "import { describe, expect, test } from 'vitest'\nimport { findAssetFile, isBuild } from '~utils'\n\ndescribe.runIf(isBuild)('css lib entry', () => {\n test('remove useless js sourcemap', async () => {\n expect(findAssetFile('linked.js.map', 'lib-entry', './')).toBeUndefined()\n })\n})", "messages": null, "tools": null} {"id": "077f729d978a16a1", "category": "code", "domain": "code", "source": "requests", "license": "Apache-2.0", "license_url": "https://spdx.org/licenses/Apache-2.0.html", "path": ".github/SECURITY.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/psf/requests", "commit": "1f6589ec3a1ee910f9a65cc3ceac60b26677bc0e", "collector": "tools/harvest.py"}, "chars": 3943, "sha256": "ca2d3e40ef23fc0c334eba1d8f05b4cee561f6872816c2c3033da25cf254d790", "text": "# Vulnerability Disclosure\n\nIf you think you have found a potential security vulnerability in\nrequests, please open a [draft Security Advisory](https://github.com/psf/requests/security/advisories/new)\nvia GitHub. We will coordinate verification and next steps through\nthat secure medium.\n\nIf English is not your first language, please try to describe the\nproblem and its impact to the best of your ability. For greater detail,\nplease use your native language and we will try our best to translate it\nusing online services.\n\nPlease also include the code you used to find the problem and the\nshortest amount of code necessary to reproduce it.\n\nPlease do not disclose this to anyone else. We will retrieve a CVE\nidentifier if necessary and give you full credit under whatever name or\nalias you provide. We will only request an identifier when we have a fix\nand can publish it in a release.\n\nWe will respect your privacy and will only publicize your involvement if\nyou grant us permission.\n\n## Process\n\nThis following information discusses the process the requests project\nfollows in response to vulnerability disclosures. If you are disclosing\na vulnerability, this section of the documentation lets you know how we\nwill respond to your disclosure.\n\n### Timeline\n\nWhen you report an issue, one of the project members will respond to you\nwithin two days *at the outside*. In most cases responses will be\nfaster, usually within 12 hours. This initial response will at the very\nleast confirm receipt of the report.\n\nIf we were able to rapidly reproduce the issue, the initial response\nwill also contain confirmation of the issue. If we are not, we will\noften ask for more information about the reproduction scenario.\n\nOur goal is to have a fix for any vulnerability released within two\nweeks of the initial disclosure. This may potentially involve shipping\nan interim release that simply disables function while a more mature fix\ncan be prepared, but will in the vast majority of cases mean shipping a\ncomplete release as soon as possible.\n\nThroughout the fix process we will keep you up to speed with how the fix\nis progressing. Once the fix is prepared, we will notify you that we\nbelieve we have a fix. Often we will ask you to confirm the fix resolves\nthe problem in your environment, especially if we are not confident of\nour reproduction scenario.\n\nAt this point, we will prepare for the release. We will obtain a CVE\nnumber if one is required, providing you with full credit for the\ndiscovery. We will also decide on a planned release date, and let you\nknow when it is. This release date will *always* be on a weekday.\n\nAt this point we will reach out to our major downstream packagers to\nnotify them of an impending security-related patch so they can make\narrangements. In addition, these packagers will be provided with the\nintended patch ahead of time, to ensure that they are able to promptly\nrelease their downstream packages. Currently the list of people we\nactively contact *ahead of a public release* is:\n\n- Python Maintenance Team, Red Hat (python-maint@redhat.com)\n- Daniele Tricoli, Debian (@eriol)\n\nWe will notify these individuals at least a week ahead of our planned\nrelease date to ensure that they have sufficient time to prepare. If you\nbelieve you should be on this list, please let one of the maintainers\nknow at one of the email addresses at the top of this article.\n\nOn release day, we will push the patch to our public repository, along\nwith an updated changelog that describes the issue and credits you. We\nwill then issue a PyPI release containing the patch.\n\nAt this point, we will publicise the release. This will involve mails to\nmailing lists, Tweets, and all other communication mechanisms available\nto the core team.\n\nWe will also explicitly mention which commits contain the fix to make it\neasier for other distributors and users to easily patch their own\nversions of requests if upgrading is not an option.", "messages": null, "tools": null} {"id": "07a18ca1445e6c1f", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/nlohmann_json_serialize_enum_strict.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 1121, "sha256": "bd90f7f0ccbde3f5438095669e611a2251abc8a8081301d2492d5e2cc35c92f6", "text": "#include \n#include \n\nusing json = nlohmann::json;\n\nnamespace ns\n{\nenum TaskState\n{\n TS_STOPPED,\n TS_RUNNING,\n TS_COMPLETED,\n TS_INVALID = -1\n};\n\nNLOHMANN_JSON_SERIALIZE_ENUM_STRICT(TaskState,\n{\n { TS_INVALID, nullptr },\n { TS_STOPPED, \"stopped\" },\n { TS_RUNNING, \"running\" },\n { TS_COMPLETED, \"completed\" }\n})\n\nenum class Color\n{\n red, green, blue, unknown\n};\n\nNLOHMANN_JSON_SERIALIZE_ENUM_STRICT(Color,\n{\n { Color::unknown, \"unknown\" }, { Color::red, \"red\" },\n { Color::green, \"green\" }, { Color::blue, \"blue\" }\n})\n} // namespace ns\n\nint main()\n{\n // serialization\n json j_stopped = ns::TS_STOPPED;\n json j_red = ns::Color::red;\n std::cout << \"ns::TS_STOPPED -> \" << j_stopped\n << \", ns::Color::red -> \" << j_red << std::endl;\n\n // deserialization\n json j_running = \"running\";\n json j_blue = \"blue\";\n auto running = j_running.get();\n auto blue = j_blue.get();\n std::cout << j_running << \" -> \" << running\n << \", \" << j_blue << \" -> \" << static_cast(blue) << std::endl;\n\n}", "messages": null, "tools": null} {"id": "083f4c0509096f0d", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/assets/__tests__/assets.spec.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 27735, "sha256": "5c5434c7620e5fcbf282b4e617d0078f2a26ea30c1eec6f50fa25ddda39f5a04", "text": "import path from 'node:path'\nimport { describe, expect, test } from 'vitest'\nimport {\n browserLogs,\n editFile,\n findAssetFile,\n getBg,\n getColor,\n isBuild,\n isBundled,\n isBundledDev,\n isServe,\n listAssets,\n notifyRebuildComplete,\n page,\n readFile,\n readManifest,\n serverLogs,\n viteTestUrl,\n watcher,\n} from '~utils'\n\nconst assetMatch = isBundled\n ? /\\/foo\\/bar\\/assets\\/asset-[-\\w]{8}\\.png/\n : '/foo/bar/nested/asset.png'\n\nconst encodedAssetMatch = isBundled\n ? /\\/foo\\/bar\\/assets\\/asset_small_-[-\\w]{8}\\.png/\n : '/foo/bar/nested/asset[small].png'\n\nconst iconMatch = `/foo/bar/icon.png`\n\nconst fetchPath = (p: string) => {\n return fetch(path.posix.join(viteTestUrl, p), {\n headers: { Accept: 'text/html,*/*' },\n })\n}\n\n// bundled dev turns a `?url` CSS import into a data URI, and it skips the CSS\n// pipeline while doing so. A `url()` inside that CSS keeps its original\n// relative path, which then points nowhere and gives a 404.\n// This is a real bug (vitejs/vite#22863), so the test must stay skipped here.\n// It will pass again once the bug is fixed, with no change to the test.\ntest.skipIf(isBundledDev)('should have no 404s', () => {\n browserLogs.forEach((msg) => {\n expect(msg).not.toMatch('404')\n })\n})\n\ntest.runIf(isBuild)(\n 'should not warn about VITE_ASSET tokens in image-set',\n async () => {\n expect(serverLogs).toStrictEqual(\n expect.not.arrayContaining([\n expect.stringMatching(/VITE_ASSET__.*?didn't resolve at build time/),\n ]),\n )\n },\n)\n\ntest('should get a 404 when using incorrect case', async () => {\n expect((await fetchPath('icon.png')).headers.get('Content-Type')).toBe(\n 'image/png',\n )\n // fallback to index.html\n const iconPngResult = await fetchPath('ICON.png')\n expect(iconPngResult.headers.get('Content-Type')).toBe('text/html')\n expect(iconPngResult.status).toBe(200)\n\n expect((await fetchPath('bar')).headers.get('Content-Type')).toBe('')\n // fallback to index.html\n const barResult = await fetchPath('BAR')\n expect(barResult.headers.get('Content-Type')).toContain('text/html')\n expect(barResult.status).toBe(200)\n})\n\ntest('should fallback to index.html when accessing non-existent html file', async () => {\n expect((await fetchPath('doesnt-exist.html')).status).toBe(200)\n})\n\ndescribe.runIf(isServe)('outside base', () => {\n test('should get a 404 with html', async () => {\n const res = await fetch(new URL('/baz', viteTestUrl), {\n headers: { Accept: 'text/html,*/*' },\n })\n expect(res.status).toBe(404)\n expect(res.headers.get('Content-Type')).toBe('text/html')\n })\n\n test('should get a 404 with text', async () => {\n const res = await fetch(new URL('/baz', viteTestUrl))\n expect(res.status).toBe(404)\n expect(res.headers.get('Content-Type')).toBe('text/plain')\n })\n})\n\ndescribe('injected scripts', () => {\n test('@vite/client', async () => {\n const hasClient = await page.$(\n 'script[type=\"module\"][src=\"/foo/bar/@vite/client\"]',\n )\n if (isBundled) {\n expect(hasClient).toBeFalsy()\n } else {\n expect(hasClient).toBeTruthy()\n }\n })\n\n test('html-proxy', async () => {\n const hasHtmlProxy = await page.$(\n 'script[type=\"module\"][src^=\"/foo/bar/index.html?html-proxy\"]',\n )\n if (isBundled) {\n expect(hasHtmlProxy).toBeFalsy()\n } else {\n expect(hasHtmlProxy).toBeTruthy()\n }\n })\n})\n\ndescribe('raw references from /public', () => {\n test('load raw js from /public', async () => {\n expect(await page.textContent('.raw-js')).toMatch('[success]')\n })\n\n test('load raw css from /public', async () => {\n expect(await getColor('.raw-css')).toBe('red')\n })\n})\n\ntest('import-expression from simple script', async () => {\n expect(await page.textContent('.import-expression')).toMatch(\n '[success][success]',\n )\n})\n\ndescribe('asset imports from js', () => {\n test('relative', async () => {\n expect(await page.textContent('.asset-import-relative')).toMatch(assetMatch)\n })\n\n test('absolute', async () => {\n expect(await page.textContent('.asset-import-absolute')).toMatch(assetMatch)\n })\n\n test('from /public', async () => {\n expect(await page.textContent('.public-import')).toMatch(iconMatch)\n })\n\n test('from /public (json)', async () => {\n expect(await page.textContent('.public-json-import')).toMatch(\n '/foo/bar/foo.json',\n )\n expect(await page.textContent('.public-json-import-content'))\n .toMatchInlineSnapshot(`\n \"{\n \"foo\": \"bar\"\n }\n \"\n `)\n })\n\n test('from /public (js)', async () => {\n expect(await page.textContent('.public-js-import')).toMatch(\n '/foo/bar/raw.js',\n )\n expect(await page.textContent('.public-js-import-content'))\n .toMatchInlineSnapshot(`\n \"document.querySelector('.raw-js').textContent =\n '[success] Raw js from /public loaded'\n \"\n `)\n expect(await page.textContent('.public-js-import-content-type')).toMatch(\n 'text/javascript',\n )\n })\n\n test('from /public (ts)', async () => {\n expect(await page.textContent('.public-ts-import')).toMatch(\n '/foo/bar/raw.ts',\n )\n expect(await page.textContent('.public-ts-import-content'))\n .toMatchInlineSnapshot(`\n \"export default function other() {\n return 1 + 2\n }\n \"\n `)\n // NOTE: users should configure the mime type for .ts files for preview server\n if (isServe) {\n expect(await page.textContent('.public-ts-import-content-type')).toMatch(\n 'text/javascript',\n )\n }\n })\n\n test('from /public (mts)', async () => {\n expect(await page.textContent('.public-mts-import')).toMatch(\n '/foo/bar/raw.mts',\n )\n expect(await page.textContent('.public-mts-import-content'))\n .toMatchInlineSnapshot(`\n \"export default function foobar() {\n return 1 + 2\n }\n \"\n `)\n // NOTE: users should configure the mime type for .ts files for preview server\n if (isServe) {\n expect(await page.textContent('.public-mts-import-content-type')).toMatch(\n 'text/javascript',\n )\n }\n })\n})\n\ndescribe('css url() references', () => {\n test('fonts', async () => {\n expect(\n await page.evaluate(() => {\n return (document as any).fonts.check('700 32px Inter')\n }),\n ).toBe(true)\n })\n\n test('relative', async () => {\n expect(await getBg('.css-url-relative')).toMatch(assetMatch)\n })\n\n test('encoded', async () => {\n expect(await getBg('.css-url-encoded')).toMatch(encodedAssetMatch)\n })\n\n test('image-set relative', async () => {\n const imageSet = await getBg('.css-image-set-relative')\n imageSet.split(', ').forEach((s) => {\n expect(s).toMatch(assetMatch)\n })\n })\n\n test('image-set without the url() call', async () => {\n const imageSet = await getBg('.css-image-set-without-url-call')\n imageSet.split(', ').forEach((s) => {\n expect(s).toMatch(assetMatch)\n })\n })\n\n test('image-set with var', async () => {\n const imageSet = await getBg('.css-image-set-with-var')\n imageSet.split(', ').forEach((s) => {\n expect(s).toMatch(assetMatch)\n })\n })\n\n test('image-set with mix', async () => {\n const imageSet = await getBg('.css-image-set-mix-url-var')\n imageSet.split(', ').forEach((s) => {\n expect(s).toMatch(assetMatch)\n })\n })\n\n test('image-set with base64', async () => {\n const imageSet = await getBg('.css-image-set-base64')\n expect(imageSet).toContain('image-set(url(\"data:image/png;base64,')\n })\n\n test('image-set with gradient', async () => {\n const imageSet = await getBg('.css-image-set-gradient')\n expect(imageSet).toContain('image-set(url(\"data:image/png;base64,')\n })\n\n test('image-set with multiple descriptor', async () => {\n const imageSet = await getBg('.css-image-set-multiple-descriptor')\n imageSet.split(', ').forEach((s) => {\n expect(s).toMatch(assetMatch)\n })\n })\n\n test('image-set with multiple descriptor as inline style', async () => {\n const imageSet = await getBg(\n '.css-image-set-multiple-descriptor-inline-style',\n )\n imageSet.split(', ').forEach((s) => {\n expect(s).toMatch(assetMatch)\n })\n })\n\n test('image-set and url exist at the same time.', async () => {\n const imageSet = await getBg('.image-set-and-url-exsiting-at-same-time')\n expect(imageSet).toMatch(assetMatch)\n })\n\n test('relative in @import', async () => {\n expect(await getBg('.css-url-relative-at-imported')).toMatch(assetMatch)\n })\n\n test('absolute', async () => {\n expect(await getBg('.css-url-absolute')).toMatch(assetMatch)\n })\n\n test('from /public', async () => {\n expect(await getBg('.css-url-public')).toMatch(iconMatch)\n })\n\n test('base64 inline', async () => {\n const match = isBundled\n ? `data:image/png;base64`\n : `/foo/bar/nested/icon.png`\n expect(await getBg('.css-url-base64-inline')).toMatch(match)\n expect(await getBg('.css-url-quotes-base64-inline')).toMatch(match)\n })\n\n test('no base64 inline for icon and manifest links', async () => {\n const iconEl = await page.$(`link.ico`)\n const href = await iconEl.getAttribute('href')\n expect(href).toMatch(\n isBundled ? /\\/foo\\/bar\\/assets\\/favicon-[-\\w]{8}\\.ico/ : 'favicon.ico',\n )\n\n const manifestEl = await page.$(`link[rel=\"manifest\"]`)\n const manifestHref = await manifestEl.getAttribute('href')\n expect(manifestHref).toMatch(\n isBundled\n ? /\\/foo\\/bar\\/assets\\/manifest-[-\\w]{8}\\.json/\n : 'manifest.json',\n )\n })\n\n test('multiple urls on the same line', async () => {\n const bg = await getBg('.css-url-same-line')\n expect(bg).toMatch(assetMatch)\n expect(bg).toMatch(iconMatch)\n })\n\n test('aliased', async () => {\n const bg = await getBg('.css-url-aliased')\n expect(bg).toMatch(assetMatch)\n })\n\n test('preinlined SVG', async () => {\n expect(await getBg('.css-url-preinlined-svg')).toMatch(\n /data:image\\/svg\\+xml,.+/,\n )\n })\n\n test.runIf(isBuild)('generated paths in CSS', () => {\n const css = findAssetFile(/index-[-\\w]{8}\\.css$/, 'foo')\n\n // preserve postfix query/hash\n expect(css).toMatch(`woff2?#iefix`)\n\n // generate non-relative base for public path in CSS\n expect(css).not.toMatch(`../icon.png`)\n })\n\n test('url() with svg', async () => {\n const bg = await getBg('.css-url-svg')\n expect(bg).toMatch(/data:image\\/svg\\+xml,.+/)\n expect(bg).toContain('blue')\n expect(bg).not.toContain('red')\n\n if (isServe) {\n editFile('nested/fragment-bg-hmr.svg', (code) =>\n code.replace('fill=\"blue\"', 'fill=\"red\"'),\n )\n await expect.poll(() => getBg('.css-url-svg')).toMatch('red')\n }\n })\n\n test('image-set() with svg', async () => {\n expect(await getBg('.css-image-set-svg')).toMatch(/data:image\\/svg\\+xml,.+/)\n })\n\n // bundled dev turns the `?url` CSS into a data URI, while build always\n // writes a CSS file. The svg inside that CSS is therefore never processed:\n // it is not inlined, and it does not get the base prefix.\n // Same cause as '?url import on css' below: the CSS pipeline never runs on a\n // `?url` import (vitejs/vite#22863)\n test.skipIf(isBundledDev)('url() with svg in .css?url', async () => {\n const bg = await getBg('.css-url-svg-in-url')\n expect(bg).toMatch(/data:image\\/svg\\+xml,.+/)\n expect(bg).toContain('blue')\n expect(bg).not.toContain('red')\n\n if (isServe) {\n editFile('nested/fragment-bg-hmr2.svg', (code) =>\n code.replace('fill=\"blue\"', 'fill=\"red\"'),\n )\n await expect.poll(() => getBg('.css-url-svg')).toMatch('red')\n }\n })\n\n test.runIf(isServe)('non inlined url() HMR', async () => {\n const bg = await getBg('.css-url-non-inline-hmr')\n editFile('nested/donuts-large.svg', (code) =>\n code.replace('fill=\"blue\"', 'fill=\"red\"'),\n )\n await expect.poll(() => getBg('.css-url-non-inline-hmr')).not.toBe(bg)\n })\n})\n\ndescribe('image', () => {\n test('src', async () => {\n const img = await page.$('.img-src')\n const src = await img.getAttribute('src')\n expect(src).toMatch(\n isBundled\n ? /\\/foo\\/bar\\/assets\\/html-only-asset-[-\\w]{8}\\.jpg/\n : /\\/foo\\/bar\\/nested\\/html-only-asset.jpg/,\n )\n })\n\n test('src inline', async () => {\n const img = await page.$('.img-src-inline')\n const src = await img.getAttribute('src')\n expect(src).toMatch(\n isBundled\n ? /^data:image\\/svg\\+xml,%3csvg/\n : /\\/foo\\/bar\\/nested\\/inlined.svg/,\n )\n })\n\n test('srcset', async () => {\n const img = await page.$('.img-src-set')\n const srcset = await img.getAttribute('srcset')\n srcset.split(', ').forEach((s) => {\n expect(s).toMatch(\n isBundled\n ? /\\/foo\\/bar\\/assets\\/asset-[-\\w]{8}\\.png \\dx/\n : /\\/foo\\/bar\\/nested\\/asset.png \\dx/,\n )\n })\n })\n\n test('srcset (public)', async () => {\n const img = await page.$('.img-src-set-public')\n const srcset = await img.getAttribute('srcset')\n srcset.split(', ').forEach((s) => {\n expect(s).toMatch(/\\/foo\\/bar\\/icon\\.png \\dx/)\n })\n })\n\n test('srcset (mixed)', async () => {\n const img = await page.$('.img-src-set-mixed')\n const srcset = await img.getAttribute('srcset')\n const srcs = srcset.split(', ')\n expect(srcs[1]).toMatch(\n isBundled\n ? /\\/foo\\/bar\\/assets\\/asset-[-\\w]{8}\\.png \\dx/\n : /\\/foo\\/bar\\/nested\\/asset.png \\dx/,\n )\n })\n})\n\ndescribe('meta', () => {\n test('og image', async () => {\n const meta = await page.$('.meta-og-image')\n const content = await meta.getAttribute('content')\n expect(content).toMatch(\n isBundled\n ? /\\/foo\\/bar\\/assets\\/asset-\\w{8}\\.png/\n : /\\/foo\\/bar\\/nested\\/asset.png/,\n )\n })\n})\n\ndescribe('svg fragments', () => {\n // 404 is checked already, so here we just ensure the urls end with #fragment\n // bundled dev drops the #fragment postfix from hashed asset URLs (vitejs/vite#23028)\n test.skipIf(isBundledDev)('img url', async () => {\n const img = await page.$('.svg-frag-img')\n expect(await img.getAttribute('src')).toMatch(/svg#icon-clock-view$/)\n })\n\n // bundled dev: #fragment dropped (see 'img url')\n test.skipIf(isBundledDev)('via css url()', async () => {\n expect(await getBg('.icon')).toMatch(/svg#icon-clock-view\"\\)$/)\n })\n\n test('from js import', async () => {\n const img = await page.$('.svg-frag-import')\n expect(await img.getAttribute('src')).toMatch(\n // Assert trimmed (data URI starts with < and ends with >)\n /^data:image\\/svg\\+xml,%3c.*%3e#icon-heart-view$/,\n )\n })\n\n // bundled dev: #fragment dropped (see 'img url')\n test.skipIf(isBundledDev)('url with an alias', async () => {\n expect(await getBg('.icon-clock-alias')).toMatch(\n /\\.svg#icon-clock-view\"\\)$/,\n )\n })\n})\n\ntest('Unknown extension assets import', async () => {\n expect(await page.textContent('.unknown-ext')).toMatch(\n isBundled ? 'data:application/octet-stream;' : '/nested/foo.unknown',\n )\n})\n\ntest('Unknown extension assets import with ?inline', async () => {\n expect(await page.textContent('.unknown-ext-inline')).toMatch(\n 'data:application/octet-stream;',\n )\n})\n\ntest('Asset matched by a relative path in assetsInclude import', async () => {\n expect(await page.textContent('.relative-path-assets-include')).toMatch(\n isBundled\n ? 'data:application/octet-stream;'\n : '/nested/relative-path.custom',\n )\n})\n\ntest('Asset matched by a relative path in assetsInclude import with ?inline', async () => {\n expect(\n await page.textContent('.relative-path-assets-include-inline'),\n ).toMatch('data:application/octet-stream;')\n})\n\ntest('?raw import', async () => {\n expect(await page.textContent('.raw')).toMatch('SVG')\n expect(await page.textContent('.raw-html')).toBe('
partial
\\n')\n\n if (isBuild) return\n editFile('nested/partial.html', (code) =>\n code.replace('
partial
', '
partial updated
'),\n )\n await expect\n .poll(() => page.textContent('.raw-html'))\n .toBe('
partial updated
\\n')\n\n // bundled dev logs `playground-temp/assets/nested/...` where dev logs the URL\n // path `/nested/...`. This is a gap on the vite side, not in rolldown\n // (vitejs/vite#23028). Two causes:\n // - the server never passes `cwd` to rolldown (bundledDev.ts), so module ids\n // start from process.cwd() and show where the project sits on disk\n // - bundledDevHmrClient.ts logs those ids as they are, without turning them\n // into URL paths first\n // Fix both, then remove this guard so the check runs in bundled dev too.\n if (!isBundled) {\n expect(browserLogs).toStrictEqual(\n expect.arrayContaining([\n expect.stringContaining('hot updated: /nested/partial.html?raw via'),\n ]),\n )\n }\n})\n\ntest('?no-inline svg import', async () => {\n expect(await page.textContent('.no-inline-svg')).toMatch(\n isBundled\n ? /\\/foo\\/bar\\/assets\\/fragment-[-\\w]{8}\\.svg/\n : '/foo/bar/nested/fragment.svg?no-inline',\n )\n})\n\n// bundled dev drops the ?query postfix from hashed asset URLs (build keeps ?foo=bar) (vitejs/vite#23028)\ntest.skipIf(isBundledDev)(\n '?no-inline svg import -- multiple postfix',\n async () => {\n expect(await page.textContent('.no-inline-svg-mp')).toMatch(\n isBundled\n ? /\\/foo\\/bar\\/assets\\/fragment-[-\\w]{8}\\.svg\\?foo=bar/\n : '/foo/bar/nested/fragment.svg?no-inline&foo=bar',\n )\n },\n)\n\ntest('?inline png import', async () => {\n expect(await page.textContent('.inline-png')).toMatch(\n /^data:image\\/png;base64,/,\n )\n})\n\ntest('?inline public png import', async () => {\n expect(await page.textContent('.inline-public-png')).toMatch(\n /^data:image\\/png;base64,/,\n )\n})\n\ntest('?inline public json import', async () => {\n expect(await page.textContent('.inline-public-json')).toMatch(\n /^data:application\\/json;base64,/,\n )\n})\n\ntest('?url import', async () => {\n const src = readFile('foo.js')\n expect(await page.textContent('.url')).toMatch(\n isBundled\n ? `data:text/javascript;base64,${Buffer.from(src).toString('base64')}`\n : `/foo/bar/foo.js`,\n )\n})\n\n// bundled dev turns the `?url` CSS into a data URI, while build always writes\n// a CSS file (vitejs/vite#22863).\n// After the fix, bundled dev returns the same URL shape as build. Then remove\n// the skip and change `isBuild` below to `isBundled`.\ntest.skipIf(isBundledDev)('?url import on css', async () => {\n const txt = await page.textContent('.url-css')\n expect(txt).toMatch(\n isBuild\n ? /\\/foo\\/bar\\/assets\\/icons-[-\\w]{8}\\.css/\n : '/foo/bar/css/icons.css',\n )\n})\n\ndescribe('unicode url', () => {\n test('from js import', async () => {\n const src = readFile('テスト-測試-white space.js')\n expect(await page.textContent('.unicode-url')).toMatch(\n isBundled\n ? `data:text/javascript;base64,${Buffer.from(src).toString('base64')}`\n : encodeURI(`/foo/bar/テスト-測試-white space.js`),\n )\n })\n})\n\ndescribe.runIf(isBuild)('encodeURI', () => {\n test('img src with encodeURI', async () => {\n const img = await page.$('.encodeURI')\n expect(await img.getAttribute('src')).toMatch(/^data:image\\/png;base64,/)\n })\n})\n\ntest('new URL(..., import.meta.url)', async () => {\n const imgMatch = isBundled\n ? /\\/foo\\/bar\\/assets\\/img-[-\\w]{8}\\.png/\n : '/foo/bar/import-meta-url/img.png'\n\n expect(await page.textContent('.import-meta-url')).toMatch(imgMatch)\n if (isServe) {\n const loadPromise = page.waitForEvent('load')\n const newContent = readFile('import-meta-url/img-update.png', null)\n let oldContent: Buffer\n editFile('import-meta-url/img.png', null, (_oldContent) => {\n oldContent = _oldContent\n return newContent\n })\n await loadPromise // expect reload\n await expect\n .poll(() => page.textContent('.import-meta-url'))\n .toMatch(imgMatch)\n\n const loadPromise2 = page.waitForEvent('load')\n editFile('import-meta-url/img.png', null, (_) => oldContent)\n await loadPromise2 // expect reload\n await expect\n .poll(() => page.textContent('.import-meta-url'))\n .toMatch(imgMatch)\n }\n})\n\ntest('new URL(\"@/...\", import.meta.url)', async () => {\n expect(await page.textContent('.import-meta-url-dep')).toMatch(assetMatch)\n})\n\ntest('new URL(\"/...\", import.meta.url)', async () => {\n expect(await page.textContent('.import-meta-url-base-path')).toMatch(\n iconMatch,\n )\n})\n\ntest('new URL(\"data:...\", import.meta.url)', async () => {\n const img = await page.$('.import-meta-url-data-uri-img')\n expect(await img.getAttribute('src')).toMatch(/^data:image\\/png;base64,/)\n expect(await page.textContent('.import-meta-url-data-uri')).toMatch(\n /^data:image\\/png;base64,/,\n )\n})\n\ntest('new URL(..., import.meta.url) without extension', async () => {\n expect(await page.textContent('.import-meta-url-without-extension')).toMatch(\n isBundled ? 'data:text/javascript' : 'nested/test.js',\n )\n expect(\n await page.textContent('.import-meta-url-content-without-extension'),\n ).toContain('export default class')\n})\n\ntest('new URL(`${dynamic}`, import.meta.url)', async () => {\n expect(await page.textContent('.dynamic-import-meta-url-1')).toMatch(\n isBundled ? 'data:image/png;base64' : '/foo/bar/nested/icon.png',\n )\n expect(await page.textContent('.dynamic-import-meta-url-2')).toMatch(\n assetMatch,\n )\n expect(await page.textContent('.dynamic-import-meta-url-js')).toMatch(\n isBundled ? 'data:text/javascript;base64' : '/foo/bar/nested/test.js',\n )\n})\n\n// bundled dev: ?abc postfix dropped (see '?no-inline svg import -- multiple postfix')\ntest.skipIf(isBundledDev)(\n 'new URL(`./${dynamic}?abc`, import.meta.url)',\n async () => {\n expect(await page.textContent('.dynamic-import-meta-url-1-query')).toMatch(\n isBundled ? 'data:image/png;base64' : '/foo/bar/nested/icon.png?abc',\n )\n expect(await page.textContent('.dynamic-import-meta-url-2-query')).toMatch(\n isBundled\n ? /\\/foo\\/bar\\/assets\\/asset-[-\\w]{8}\\.png\\?abc/\n : '/foo/bar/nested/asset.png?abc',\n )\n },\n)\n\n// bundled dev: ?abc postfix dropped (see '?no-inline svg import -- multiple postfix')\ntest.skipIf(isBundledDev)(\n 'new URL(`./${1 === 0 ? static : dynamic}?abc`, import.meta.url)',\n async () => {\n expect(\n await page.textContent('.dynamic-import-meta-url-1-ternary'),\n ).toMatch(\n isBundled ? 'data:image/png;base64' : '/foo/bar/nested/icon.png?abc',\n )\n expect(\n await page.textContent('.dynamic-import-meta-url-2-ternary'),\n ).toMatch(\n isBundled\n ? /\\/foo\\/bar\\/assets\\/asset-[-\\w]{8}\\.png\\?abc/\n : '/foo/bar/nested/asset.png?abc',\n )\n },\n)\n\ntest(\"new URL(/* @vite-ignore */ 'non-existent', import.meta.url)\", async () => {\n // the inlined script tag is extracted in a separate file\n const importMetaUrl = new URL(\n isBundled ? '/foo/bar/assets/index.js' : '/foo/bar/index.html',\n page.url(),\n )\n expect(await page.textContent('.non-existent-import-meta-url')).toMatch(\n new URL('non-existent', importMetaUrl).pathname,\n )\n expect(serverLogs).not.toContainEqual(\n expect.stringContaining(\"doesn't exist at build time\"),\n )\n})\n\ntest('new URL(..., import.meta.url) (multiline)', async () => {\n const assetMatch = isBundled\n ? /\\/foo\\/bar\\/assets\\/asset-[-\\w]{8}\\.png/\n : '/foo/bar/nested/asset.png'\n\n expect(await page.textContent('.import-meta-url-multiline')).toMatch(\n assetMatch,\n )\n})\n\ntest.runIf(isBuild)('manifest', async () => {\n const manifest = readManifest('foo')\n const entry = manifest['index.html']\n\n for (const file of listAssets('foo')) {\n if (file.endsWith('.css')) {\n // ignore icons-*.css and css-url-url-*.css as it's imported with ?url\n if (file.includes('icons-') || file.includes('css-url-url-')) continue\n expect(entry.css).toContain(`assets/${file}`)\n } else if (!file.endsWith('.js')) {\n expect(entry.assets).toContain(`assets/${file}`)\n }\n }\n})\n\ndescribe.runIf(isBuild)('css and assets in css in build watch', () => {\n test('css will not be lost and css does not contain undefined', async () => {\n editFile('index.html', (code) => code.replace('Assets', 'assets2'))\n await notifyRebuildComplete(watcher)\n const cssFile = findAssetFile(/index-[-\\w]+\\.css$/, 'foo')\n expect(cssFile).not.toBe('')\n expect(cssFile).not.toMatch(/undefined/)\n })\n\n test('old file is removed when the content changes', async () => {\n await expect.poll(() => page.textContent('.update-content')).toBe('hello')\n\n const oldMainJsFiles = listAssets('foo').filter((f) =>\n /index-[-\\w]+\\.js$/.test(f),\n )\n expect(oldMainJsFiles.length).toBe(1)\n const oldMainJsFile = oldMainJsFiles[0]\n\n editFile('asset/update.js', (code) => code.replace('hello', 'world2'))\n await notifyRebuildComplete(watcher)\n await page.reload()\n await expect.poll(() => page.textContent('.update-content')).toBe('world2')\n\n const newMainJsFiles = listAssets('foo').filter((f) =>\n /index-[-\\w]+\\.js$/.test(f),\n )\n expect(newMainJsFiles).not.toContain(oldMainJsFile)\n expect(newMainJsFiles.length).toBe(1)\n })\n\n test('import module.css', async () => {\n expect(await getColor('#foo')).toBe('red')\n editFile('css/foo.module.css', (code) => code.replace('red', 'blue'))\n await notifyRebuildComplete(watcher)\n await page.reload()\n expect(await getColor('#foo')).toBe('blue')\n })\n\n test('import with raw query', async () => {\n expect(await page.textContent('.raw-query')).toBe('foo')\n editFile('static/foo.txt', (code) => code.replace('foo', 'zoo2'))\n await notifyRebuildComplete(watcher)\n await page.reload()\n expect(await page.textContent('.raw-query')).toBe('zoo2')\n })\n})\n\ntest('inline style test', async () => {\n expect(await getBg('.inline-style')).toMatch(assetMatch)\n expect(await getBg('.style-url-assets')).toMatch(assetMatch)\n})\n\nif (!isBuild) {\n // bundled dev: editing a CSS file imported by an inline \n
@import scss: this should be red
\n", "messages": null, "tools": null} {"id": "6b62e2aa77d984cd", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/backend-integration/vite.config.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 1627, "sha256": "1e9a57bcb283f0b35c9b9a892f2c12b2e322e07cada7691409a83760b85a3bc1", "text": "import path from 'node:path'\nimport { globSync } from 'tinyglobby'\nimport { defineConfig, normalizePath } from 'vite'\nimport tailwind from '@tailwindcss/vite'\n\n/**\n * @returns {import('vite').Plugin}\n */\nfunction BackendIntegrationExample() {\n return {\n name: 'backend-integration',\n config() {\n const projectRoot = import.meta.dirname\n const sourceCodeDir = path.join(projectRoot, 'frontend')\n const root = path.join(sourceCodeDir, 'entrypoints')\n const outDir = path.relative(root, path.join(projectRoot, 'dist/dev'))\n\n const entrypoints = globSync(`${normalizePath(root)}/**/*`, {\n absolute: true,\n expandDirectories: false,\n onlyFiles: true,\n }).map((filename) => [path.relative(root, filename), filename])\n\n entrypoints.push(['tailwindcss-colors', 'tailwindcss/colors.js'])\n entrypoints.push(['bar.css', path.resolve(projectRoot, './dir/foo.css')])\n entrypoints.push([\n 'bar.custom',\n path.resolve(projectRoot, './dir/custom.css'),\n ])\n\n return {\n input: Object.fromEntries(entrypoints),\n server: {\n // same port in playground/test-utils.ts\n port: 5009,\n strictPort: true,\n origin: 'http://localhost:5009',\n },\n preview: {\n port: 5009,\n },\n build: {\n manifest: true,\n outDir,\n },\n root,\n resolve: {\n alias: {\n '~': sourceCodeDir,\n },\n },\n }\n },\n }\n}\n\nexport default defineConfig({\n base: '/dev/',\n plugins: [BackendIntegrationExample(), tailwind()],\n})", "messages": null, "tools": null} {"id": "6ba1c9611d091693", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/src/unit-udt.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 24988, "sha256": "b811cf21e93fd3d324e10721de62275a01700f6cde60b00f7bb78f42bb0e2b16", "text": "// __ _____ _____ _____\n// __| | __| | | | JSON for Modern C++ (supporting code)\n// | | |__ | | | | | | version 3.12.0\n// |_____|_____|_____|_|___| https://github.com/nlohmann/json\n//\n// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann \n// SPDX-License-Identifier: MIT\n\n#include \"doctest_compatibility.h\"\n\n// disable -Wnoexcept due to class Evil\nDOCTEST_GCC_SUPPRESS_WARNING_PUSH\nDOCTEST_GCC_SUPPRESS_WARNING(\"-Wnoexcept\")\n\n// skip tests if JSON_DisableEnumSerialization=ON (#4384)\n#if defined(JSON_DISABLE_ENUM_SERIALIZATION) && (JSON_DISABLE_ENUM_SERIALIZATION == 1)\n #define SKIP_TESTS_FOR_ENUM_SERIALIZATION\n#endif\n\n#include \nusing nlohmann::json;\n#ifdef JSON_TEST_NO_GLOBAL_UDLS\n using namespace nlohmann::literals; // NOLINT(google-build-using-namespace)\n#endif\n\n#include \n#include \n#include \n#include \n\nnamespace udt\n{\nenum class country\n{\n china,\n france,\n russia\n};\n\nstruct age\n{\n int m_val;\n age(int rhs = 0) : m_val(rhs) {}\n};\n\nstruct name\n{\n std::string m_val;\n name(std::string rhs = \"\") : m_val(std::move(rhs)) {}\n};\n\nstruct address\n{\n std::string m_val;\n address(std::string rhs = \"\") : m_val(std::move(rhs)) {}\n};\n\nstruct person\n{\n age m_age{}; // NOLINT(readability-redundant-member-init)\n name m_name{}; // NOLINT(readability-redundant-member-init)\n country m_country{}; // NOLINT(readability-redundant-member-init)\n person() = default;\n person(const age& a, name n, const country& c) : m_age(a), m_name(std::move(n)), m_country(c) {}\n};\n\nstruct contact\n{\n person m_person{}; // NOLINT(readability-redundant-member-init)\n address m_address{}; // NOLINT(readability-redundant-member-init)\n contact() = default;\n contact(person p, address a) : m_person(std::move(p)), m_address(std::move(a)) {}\n};\n\nenum class book_id : std::uint64_t;\n\nstruct contact_book\n{\n name m_book_name{}; // NOLINT(readability-redundant-member-init)\n book_id m_book_id{};\n std::vector m_contacts{}; // NOLINT(readability-redundant-member-init)\n contact_book() = default;\n contact_book(name n, book_id i, std::vector c) : m_book_name(std::move(n)), m_book_id(i), m_contacts(std::move(c)) {}\n};\n} // namespace udt\n\n// to_json methods\nnamespace udt\n{\n// templates because of the custom_json tests (see below)\ntemplate \nstatic void to_json(BasicJsonType& j, age a)\n{\n j = a.m_val;\n}\n\ntemplate \nstatic void to_json(BasicJsonType& j, const name& n)\n{\n j = n.m_val;\n}\n\ntemplate \nstatic void to_json(BasicJsonType& j, country c)\n{\n switch (c)\n {\n case country::china:\n j = \"中华人民共和国\";\n return;\n case country::france:\n j = \"France\";\n return;\n case country::russia:\n j = \"Российская Федерация\";\n return;\n default:\n break;\n }\n}\n\ntemplate \nstatic void to_json(BasicJsonType& j, const person& p)\n{\n j = BasicJsonType{{\"age\", p.m_age}, {\"name\", p.m_name}, {\"country\", p.m_country}};\n}\n\nstatic void to_json(nlohmann::json& j, const address& a)\n{\n j = a.m_val;\n}\n\nstatic void to_json(nlohmann::json& j, const contact& c)\n{\n j = json{{\"person\", c.m_person}, {\"address\", c.m_address}};\n}\n\nstatic void to_json(nlohmann::json& j, const contact_book& cb)\n{\n j = json{{\"name\", cb.m_book_name},\n#ifndef SKIP_TESTS_FOR_ENUM_SERIALIZATION\n {\"id\", cb.m_book_id},\n#endif\n {\"contacts\", cb.m_contacts}};\n}\n\n// operators\nstatic bool operator==(age lhs, age rhs)\n{\n return lhs.m_val == rhs.m_val;\n}\n\nstatic bool operator==(const address& lhs, const address& rhs)\n{\n return lhs.m_val == rhs.m_val;\n}\n\nstatic bool operator==(const name& lhs, const name& rhs)\n{\n return lhs.m_val == rhs.m_val;\n}\n\nstatic bool operator==(const person& lhs, const person& rhs)\n{\n return std::tie(lhs.m_name, lhs.m_age) == std::tie(rhs.m_name, rhs.m_age);\n}\n\nstatic bool operator==(const contact& lhs, const contact& rhs)\n{\n return std::tie(lhs.m_person, lhs.m_address) ==\n std::tie(rhs.m_person, rhs.m_address);\n}\n\nstatic bool operator==(const contact_book& lhs, const contact_book& rhs)\n{\n return std::tie(lhs.m_book_name, lhs.m_book_id, lhs.m_contacts) ==\n std::tie(rhs.m_book_name, rhs.m_book_id, rhs.m_contacts);\n}\n} // namespace udt\n\n// from_json methods\nnamespace udt\n{\ntemplate \nstatic void from_json(const BasicJsonType& j, age& a)\n{\n a.m_val = j.template get();\n}\n\ntemplate \nstatic void from_json(const BasicJsonType& j, name& n)\n{\n n.m_val = j.template get();\n}\n\ntemplate \nstatic void from_json(const BasicJsonType& j, country& c)\n{\n const auto str = j.template get();\n const std::map m =\n {\n {\"中华人民共和国\", country::china},\n {\"France\", country::france},\n {\"Российская Федерация\", country::russia}\n };\n\n const auto it = m.find(str);\n // TODO(nlohmann) test exceptions\n c = it->second;\n}\n\ntemplate \nstatic void from_json(const BasicJsonType& j, person& p)\n{\n p.m_age = j[\"age\"].template get();\n p.m_name = j[\"name\"].template get();\n p.m_country = j[\"country\"].template get();\n}\n\nstatic void from_json(const nlohmann::json& j, address& a)\n{\n a.m_val = j.get();\n}\n\nstatic void from_json(const nlohmann::json& j, contact& c)\n{\n c.m_person = j[\"person\"].get();\n c.m_address = j[\"address\"].get
();\n}\n\nstatic void from_json(const nlohmann::json& j, contact_book& cb)\n{\n cb.m_book_name = j[\"name\"].get();\n#ifndef SKIP_TESTS_FOR_ENUM_SERIALIZATION\n cb.m_book_id = j[\"id\"].get();\n#endif\n cb.m_contacts = j[\"contacts\"].get>();\n}\n} // namespace udt\n\nTEST_CASE(\"basic usage\" * doctest::test_suite(\"udt\"))\n{\n\n // a bit narcissistic maybe :) ?\n const udt::age a\n {\n 23\n };\n const udt::name n{\"theo\"};\n const udt::country c{udt::country::france};\n const udt::person sfinae_addict{a, n, c};\n const udt::person senior_programmer{{42}, {\"王芳\"}, udt::country::china};\n const udt::address addr{\"Paris\"};\n const udt::contact cpp_programmer{sfinae_addict, addr};\n const udt::book_id large_id{static_cast(static_cast(1) << 63)}; // verify large unsigned enums are handled correctly\n const udt::contact_book book{{\"C++\"}, static_cast(42u), {cpp_programmer, {senior_programmer, addr}}};\n\n SECTION(\"conversion to json via free-functions\")\n {\n CHECK(json(a) == json(23));\n CHECK(json(n) == json(\"theo\"));\n CHECK(json(c) == json(\"France\"));\n CHECK(json(sfinae_addict) == R\"({\"name\":\"theo\", \"age\":23, \"country\":\"France\"})\"_json);\n CHECK(json(\"Paris\") == json(addr));\n CHECK(json(cpp_programmer) ==\n R\"({\"person\" : {\"age\":23, \"name\":\"theo\", \"country\":\"France\"}, \"address\":\"Paris\"})\"_json);\n#ifndef SKIP_TESTS_FOR_ENUM_SERIALIZATION\n CHECK(json(large_id) == json(static_cast(1) << 63));\n CHECK(json(large_id) > 0u);\n CHECK(to_string(json(large_id)) == \"9223372036854775808\");\n CHECK(json(large_id).is_number_unsigned());\n#endif\n\n#ifndef SKIP_TESTS_FOR_ENUM_SERIALIZATION\n CHECK(\n json(book) ==\n R\"({\"name\":\"C++\", \"id\":42, \"contacts\" : [{\"person\" : {\"age\":23, \"name\":\"theo\", \"country\":\"France\"}, \"address\":\"Paris\"}, {\"person\" : {\"age\":42, \"country\":\"中华人民共和国\", \"name\":\"王芳\"}, \"address\":\"Paris\"}]})\"_json);\n#else\n CHECK(\n json(book) ==\n R\"({\"name\":\"C++\", \"contacts\" : [{\"person\" : {\"age\":23, \"name\":\"theo\", \"country\":\"France\"}, \"address\":\"Paris\"}, {\"person\" : {\"age\":42, \"country\":\"中华人民共和国\", \"name\":\"王芳\"}, \"address\":\"Paris\"}]})\"_json);\n#endif\n\n }\n\n SECTION(\"conversion from json via free-functions\")\n {\n const auto big_json =\n R\"({\"name\":\"C++\", \"id\":42, \"contacts\" : [{\"person\" : {\"age\":23, \"name\":\"theo\", \"country\":\"France\"}, \"address\":\"Paris\"}, {\"person\" : {\"age\":42, \"country\":\"中华人民共和国\", \"name\":\"王芳\"}, \"address\":\"Paris\"}]})\"_json;\n SECTION(\"via explicit calls to get\")\n {\n const auto parsed_book = big_json.get();\n const auto book_name = big_json[\"name\"].get();\n#ifndef SKIP_TESTS_FOR_ENUM_SERIALIZATION\n const auto book_id = big_json[\"id\"].get();\n#endif\n const auto contacts =\n big_json[\"contacts\"].get>();\n const auto contact_json = big_json[\"contacts\"].at(0);\n const auto contact = contact_json.get();\n const auto person = contact_json[\"person\"].get();\n const auto address = contact_json[\"address\"].get();\n const auto age = contact_json[\"person\"][\"age\"].get();\n const auto country =\n contact_json[\"person\"][\"country\"].get();\n const auto name = contact_json[\"person\"][\"name\"].get();\n\n CHECK(age == a);\n CHECK(name == n);\n CHECK(country == c);\n CHECK(address == addr);\n CHECK(person == sfinae_addict);\n CHECK(contact == cpp_programmer);\n CHECK(contacts == book.m_contacts);\n CHECK(book_name == udt::name{\"C++\"});\n#ifndef SKIP_TESTS_FOR_ENUM_SERIALIZATION\n CHECK(book_id == book.m_book_id);\n CHECK(book == parsed_book);\n#endif\n }\n\n SECTION(\"via explicit calls to get_to\")\n {\n udt::person person;\n udt::name name;\n\n json person_json = big_json[\"contacts\"][0][\"person\"];\n CHECK(person_json.get_to(person) == sfinae_addict);\n\n // correct reference gets returned\n person_json[\"name\"].get_to(name).m_val = \"new name\";\n CHECK(name.m_val == \"new name\");\n }\n\n#if JSON_USE_IMPLICIT_CONVERSIONS\n SECTION(\"implicit conversions\")\n {\n const udt::contact_book parsed_book = big_json;\n const udt::name book_name = big_json[\"name\"];\n#ifndef SKIP_TESTS_FOR_ENUM_SERIALIZATION\n const udt::book_id book_id = big_json[\"id\"];\n#endif\n const std::vector contacts = big_json[\"contacts\"];\n const auto contact_json = big_json[\"contacts\"].at(0);\n const udt::contact contact = contact_json;\n const udt::person person = contact_json[\"person\"];\n const udt::address address = contact_json[\"address\"];\n const udt::age age = contact_json[\"person\"][\"age\"];\n const udt::country country = contact_json[\"person\"][\"country\"];\n const udt::name name = contact_json[\"person\"][\"name\"];\n\n CHECK(age == a);\n CHECK(name == n);\n CHECK(country == c);\n CHECK(address == addr);\n CHECK(person == sfinae_addict);\n CHECK(contact == cpp_programmer);\n CHECK(contacts == book.m_contacts);\n CHECK(book_name == udt::name{\"C++\"});\n#ifndef SKIP_TESTS_FOR_ENUM_SERIALIZATION\n CHECK(book_id == static_cast(42u));\n CHECK(book == parsed_book);\n#endif\n }\n#endif\n }\n}\n\nnamespace udt\n{\nstruct legacy_type\n{\n std::string number{}; // NOLINT(readability-redundant-member-init)\n legacy_type() = default;\n legacy_type(std::string n) : number(std::move(n)) {}\n};\n} // namespace udt\n\nnamespace nlohmann\n{\ntemplate \nstruct adl_serializer>\n{\n static void to_json(json& j, const std::shared_ptr& opt)\n {\n if (opt)\n {\n j = *opt;\n }\n else\n {\n j = nullptr;\n }\n }\n\n static void from_json(const json& j, std::shared_ptr& opt)\n {\n if (j.is_null())\n {\n opt = nullptr;\n }\n else\n {\n opt.reset(new T(j.get())); // NOLINT(cppcoreguidelines-owning-memory)\n }\n }\n};\n\ntemplate <>\nstruct adl_serializer\n{\n static void to_json(json& j, const udt::legacy_type& l)\n {\n j = std::stoi(l.number);\n }\n\n static void from_json(const json& j, udt::legacy_type& l)\n {\n l.number = std::to_string(j.get());\n }\n};\n} // namespace nlohmann\n\nTEST_CASE(\"adl_serializer specialization\" * doctest::test_suite(\"udt\"))\n{\n SECTION(\"partial specialization\")\n {\n SECTION(\"to_json\")\n {\n std::shared_ptr optPerson;\n\n json j = optPerson;\n CHECK(j.is_null());\n\n optPerson.reset(new udt::person{{42}, {\"John Doe\"}, udt::country::russia}); // NOLINT(cppcoreguidelines-owning-memory,modernize-make-shared)\n j = optPerson;\n CHECK_FALSE(j.is_null());\n\n CHECK(j.get() == *optPerson);\n }\n\n SECTION(\"from_json\")\n {\n auto person = udt::person{{42}, {\"John Doe\"}, udt::country::russia};\n json j = person;\n\n auto optPerson = j.get>();\n REQUIRE(optPerson);\n CHECK(*optPerson == person);\n\n j = nullptr;\n optPerson = j.get>();\n CHECK(!optPerson);\n }\n }\n\n SECTION(\"total specialization\")\n {\n SECTION(\"to_json\")\n {\n udt::legacy_type const lt{\"4242\"};\n\n json const j = lt;\n CHECK(j.get() == 4242);\n }\n\n SECTION(\"from_json\")\n {\n json const j = 4242;\n auto lt = j.get();\n CHECK(lt.number == \"4242\");\n }\n }\n}\n\nnamespace nlohmann\n{\ntemplate <>\nstruct adl_serializer>\n{\n using type = std::vector;\n static void to_json(json& j, const type& /*type*/)\n {\n j = \"hijacked!\";\n }\n\n static void from_json(const json& /*unnamed*/, type& opt)\n {\n opt = {42.0, 42.0, 42.0};\n }\n\n // preferred version\n static type from_json(const json& /*unnamed*/)\n {\n return {4.0, 5.0, 6.0};\n }\n};\n} // namespace nlohmann\n\nTEST_CASE(\"even supported types can be specialized\" * doctest::test_suite(\"udt\"))\n{\n json const j = std::vector {1.0, 2.0, 3.0};\n CHECK(j.dump() == R\"(\"hijacked!\")\");\n auto f = j.get>();\n // the single argument from_json method is preferred\n CHECK((f == std::vector {4.0, 5.0, 6.0}));\n}\n\nnamespace nlohmann\n{\ntemplate \nstruct adl_serializer>\n{\n static void to_json(json& j, const std::unique_ptr& opt)\n {\n if (opt)\n {\n j = *opt;\n }\n else\n {\n j = nullptr;\n }\n }\n\n // this is the overload needed for non-copyable types,\n static std::unique_ptr from_json(const json& j)\n {\n if (j.is_null())\n {\n return nullptr;\n }\n\n return std::unique_ptr(new T(j.get()));\n }\n};\n} // namespace nlohmann\n\nTEST_CASE(\"Non-copyable types\" * doctest::test_suite(\"udt\"))\n{\n SECTION(\"to_json\")\n {\n std::unique_ptr optPerson;\n\n json j = optPerson;\n CHECK(j.is_null());\n\n optPerson.reset(new udt::person{{42}, {\"John Doe\"}, udt::country::russia}); // NOLINT(cppcoreguidelines-owning-memory,modernize-make-unique)\n j = optPerson;\n CHECK_FALSE(j.is_null());\n\n CHECK(j.get() == *optPerson);\n }\n\n SECTION(\"from_json\")\n {\n auto person = udt::person{{42}, {\"John Doe\"}, udt::country::russia};\n json j = person;\n\n auto optPerson = j.get>();\n REQUIRE(optPerson);\n CHECK(*optPerson == person);\n\n j = nullptr;\n optPerson = j.get>();\n CHECK(!optPerson);\n }\n}\n\n// custom serializer - advanced usage\n// pack structs that are pod-types (but not scalar types)\n// relies on adl for any other type\ntemplate \nstruct pod_serializer\n{\n // use adl for non-pods, or scalar types\n template <\n typename BasicJsonType, typename U = T,\n typename std::enable_if <\n !(std::is_pod::value && std::is_class::value), int >::type = 0 >\n static void from_json(const BasicJsonType& j, U& t)\n {\n using nlohmann::from_json;\n from_json(j, t);\n }\n\n // special behaviour for pods\n template < typename BasicJsonType, typename U = T,\n typename std::enable_if <\n std::is_pod::value && std::is_class::value, int >::type = 0 >\n static void from_json(const BasicJsonType& j, U& t)\n {\n std::uint64_t value = 0;\n // The following block is no longer relevant in this serializer, make another one that shows the issue\n // the problem arises only when one from_json method is defined without any constraint\n //\n // Why cannot we simply use: j.get() ?\n // Well, with the current experiment, the get method looks for a from_json\n // function, which we are currently defining!\n // This would end up in a stack overflow. Calling nlohmann::from_json is a\n // workaround (is it?).\n // I shall find a good way to avoid this once all constructors are converted\n // to free methods\n //\n // In short, constructing a json by constructor calls to_json\n // calling get calls from_json, for now, we cannot do this in custom\n // serializers\n nlohmann::from_json(j, value);\n auto* bytes = static_cast(static_cast(&value)); // NOLINT(bugprone-casting-through-void)\n std::memcpy(&t, bytes, sizeof(value));\n }\n\n template <\n typename BasicJsonType, typename U = T,\n typename std::enable_if <\n !(std::is_pod::value && std::is_class::value), int >::type = 0 >\n static void to_json(BasicJsonType& j, const T& t)\n {\n using nlohmann::to_json;\n to_json(j, t);\n }\n\n template < typename BasicJsonType, typename U = T,\n typename std::enable_if <\n std::is_pod::value && std::is_class::value, int >::type = 0 >\n static void to_json(BasicJsonType& j, const T& t) noexcept\n {\n const auto* bytes = static_cast< const unsigned char*>(static_cast(&t)); // NOLINT(bugprone-casting-through-void)\n std::uint64_t value = 0;\n std::memcpy(&value, bytes, sizeof(value));\n nlohmann::to_json(j, value);\n }\n};\n\nnamespace udt\n{\nstruct small_pod\n{\n int begin;\n char middle;\n short end;\n};\n\nstruct non_pod\n{\n std::string s{}; // NOLINT(readability-redundant-member-init)\n non_pod() = default;\n non_pod(std::string S) : s(std::move(S)) {}\n};\n\ntemplate \nstatic void to_json(BasicJsonType& j, const non_pod& np)\n{\n j = np.s;\n}\n\ntemplate \nstatic void from_json(const BasicJsonType& j, non_pod& np)\n{\n np.s = j.template get();\n}\n\nstatic bool operator==(small_pod lhs, small_pod rhs) noexcept\n{\n return std::tie(lhs.begin, lhs.middle, lhs.end) ==\n std::tie(rhs.begin, rhs.middle, rhs.end);\n}\n\nstatic bool operator==(const non_pod& lhs, const non_pod& rhs) noexcept\n{\n return lhs.s == rhs.s;\n}\n\nstatic std::ostream& operator<<(std::ostream& os, small_pod l)\n{\n return os << \"begin: \" << l.begin << \", middle: \" << l.middle << \", end: \" << l.end;\n}\n} // namespace udt\n\nTEST_CASE(\"custom serializer for pods\" * doctest::test_suite(\"udt\"))\n{\n using custom_json =\n nlohmann::basic_json;\n\n auto p = udt::small_pod{42, '/', 42};\n custom_json const j = p;\n\n auto p2 = j.get();\n\n CHECK(p == p2);\n\n auto np = udt::non_pod{{\"non-pod\"}};\n custom_json const j2 = np;\n auto np2 = j2.get();\n CHECK(np == np2);\n}\n\ntemplate \nstruct another_adl_serializer;\n\nusing custom_json = nlohmann::basic_json;\n\ntemplate \nstruct another_adl_serializer\n{\n static void from_json(const custom_json& j, T& t)\n {\n using nlohmann::from_json;\n from_json(j, t);\n }\n\n static void to_json(custom_json& j, const T& t)\n {\n using nlohmann::to_json;\n to_json(j, t);\n }\n};\n\nTEST_CASE(\"custom serializer that does adl by default\" * doctest::test_suite(\"udt\"))\n{\n auto me = udt::person{{23}, {\"theo\"}, udt::country::france};\n\n json const j = me;\n custom_json const cj = me;\n\n CHECK(j.dump() == cj.dump());\n\n CHECK(me == j.get());\n CHECK(me == cj.get());\n}\n\nTEST_CASE(\"different basic_json types conversions\")\n{\n SECTION(\"null\")\n {\n json const j;\n const custom_json cj = j;\n CHECK(cj == nullptr);\n }\n\n SECTION(\"boolean\")\n {\n json const j = true;\n const custom_json cj = j;\n CHECK(cj == true);\n }\n\n SECTION(\"discarded\")\n {\n json const j(json::value_t::discarded);\n custom_json cj;\n CHECK_NOTHROW(cj = j);\n CHECK(cj.type() == custom_json::value_t::discarded);\n }\n\n SECTION(\"array\")\n {\n json const j = {1, 2, 3};\n custom_json const cj = j;\n CHECK((cj == std::vector {1, 2, 3}));\n }\n\n SECTION(\"integer\")\n {\n json const j = 42;\n const custom_json cj = j;\n CHECK(cj == 42);\n }\n\n SECTION(\"float\")\n {\n json const j = 42.0;\n const custom_json cj = j;\n CHECK(cj == 42.0);\n }\n\n SECTION(\"unsigned\")\n {\n json const j = 42u;\n const custom_json cj = j;\n CHECK(cj == 42u);\n }\n\n SECTION(\"string\")\n {\n json const j = \"forty-two\";\n const custom_json cj = j;\n CHECK(cj == \"forty-two\");\n }\n\n SECTION(\"binary\")\n {\n json j = json::binary({1, 2, 3}, 42);\n custom_json cj = j;\n CHECK(cj.get_binary().subtype() == 42);\n const std::vector& cv = cj.get_binary();\n std::vector v = j.get_binary();\n CHECK(cv == v);\n }\n\n SECTION(\"object\")\n {\n json const j = {{\"forty\", \"two\"}};\n const custom_json cj = j;\n auto m = j.get>();\n CHECK(cj == m);\n }\n\n SECTION(\"get\")\n {\n json const j = 42;\n const custom_json cj = j.get();\n CHECK(cj == 42);\n }\n}\n\nnamespace\n{\nstruct incomplete;\n\n// std::is_constructible is broken on macOS' libc++\n// use the cppreference implementation\n\ntemplate \nstruct is_constructible_patched : std::false_type {};\n\ntemplate \nstruct is_constructible_patched())))> : std::true_type {};\n} // namespace\n\nTEST_CASE(\"an incomplete type does not trigger a compiler error in non-evaluated context\" * doctest::test_suite(\"udt\"))\n{\n static_assert(!is_constructible_patched::value, \"\");\n}\n\nnamespace\n{\nclass Evil\n{\n public:\n Evil() = default;\n template \n Evil(const T& t) : m_i(sizeof(t))\n {\n static_cast(t); // fix MSVC's C4100 warning\n }\n\n int m_i = 0;\n};\n\nvoid from_json(const json& /*unused*/, Evil& /*unused*/) {}\n} // namespace\n\nTEST_CASE(\"Issue #924\")\n{\n // Prevent get>() to throw\n auto j = json::array();\n\n CHECK_NOTHROW(j.get());\n CHECK_NOTHROW(j.get>());\n\n // silence Wunused-template warnings\n const Evil e(1);\n CHECK(e.m_i >= 0);\n\n // suppress warning: function \"::Evil::Evil(T) [with T=std::string]\" was declared but never referenced [declared_but_not_referenced]\n const Evil e2(std::string(\"foo\"));\n CHECK(e2.m_i >= 0);\n}\n\nTEST_CASE(\"Issue #1237\")\n{\n struct non_convertible_type {};\n static_assert(!std::is_convertible::value, \"\");\n}\n\nnamespace\n{\nclass no_iterator_type\n{\n public:\n no_iterator_type(std::initializer_list l)\n : _v(l)\n {}\n\n std::vector::const_iterator begin() const\n {\n return _v.begin();\n }\n\n std::vector::const_iterator end() const\n {\n return _v.end();\n }\n\n private:\n std::vector _v;\n};\n} // namespace\n\nTEST_CASE(\"compatible array type, without iterator type alias\")\n{\n no_iterator_type const vec{1, 2, 3};\n json const j = vec;\n}\n\nDOCTEST_GCC_SUPPRESS_WARNING_POP", "messages": null, "tools": null} {"id": "6bcb46937d17dc5c", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/at__object_t_key_type.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 992, "sha256": "1b6711ab2ac848b332577bd638ff5d50cd412422705adafbf99f1deea70ce300", "text": "#include \n#include \n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON object\n json object =\n {\n {\"the good\", \"il buono\"},\n {\"the bad\", \"il cattivo\"},\n {\"the ugly\", \"il brutto\"}\n };\n\n // output element with key \"the ugly\"\n std::cout << object.at(\"the ugly\") << '\\n';\n\n // change element with key \"the bad\"\n object.at(\"the bad\") = \"il cattivo\";\n\n // output changed array\n std::cout << object << '\\n';\n\n // exception type_error.304\n try\n {\n // use at() on a non-object type\n json str = \"I am a string\";\n str.at(\"the good\") = \"Another string\";\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << '\\n';\n }\n\n // exception out_of_range.401\n try\n {\n // try to write at a nonexisting key\n object.at(\"the fast\") = \"il rapido\";\n }\n catch (const json::out_of_range& e)\n {\n std::cout << e.what() << '\\n';\n }\n}", "messages": null, "tools": null} {"id": "6c670d4be1089994", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/worker/emit-chunk-sub-worker.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 270, "sha256": "a4fdd3d11a7507f80eb800be46cda3d9a0a021cad5efc0327f85e5a568246525", "text": "Promise.all([\n import('./module-and-worker'),\n import('./modules/module2'),\n import('./modules/module3'),\n]).then((data) => {\n const _data = { ...data[0], ...data[1], ...data[2] }\n self.postMessage(_data)\n})\n\n// for sourcemap\nconsole.log('emit-chunk-sub-worker.js')", "messages": null, "tools": null} {"id": "6cba53cdf8a50393", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/src/unit-json_patch.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 51826, "sha256": "479bef8a89172f397f94e082478dd8a57524e5e32c387d5a7f18d96a16d8f66e", "text": "// __ _____ _____ _____\n// __| | __| | | | JSON for Modern C++ (supporting code)\n// | | |__ | | | | | | version 3.12.0\n// |_____|_____|_____|_|___| https://github.com/nlohmann/json\n//\n// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann \n// SPDX-License-Identifier: MIT\n\n#include \"doctest_compatibility.h\"\n\n#include \nusing nlohmann::json;\n#ifdef JSON_TEST_NO_GLOBAL_UDLS\n using namespace nlohmann::literals; // NOLINT(google-build-using-namespace)\n#endif\n\n#include \n#include \"make_test_data_available.hpp\"\n\nTEST_CASE(\"JSON patch\")\n{\n SECTION(\"examples from RFC 6902\")\n {\n SECTION(\"4. Operations\")\n {\n // the ordering of members in JSON objects is not significant:\n const json op1 = R\"({ \"op\": \"add\", \"path\": \"/a/b/c\", \"value\": \"foo\" })\"_json;\n const json op2 = R\"({ \"path\": \"/a/b/c\", \"op\": \"add\", \"value\": \"foo\" })\"_json;\n const json op3 = R\"({ \"value\": \"foo\", \"path\": \"/a/b/c\", \"op\": \"add\" })\"_json;\n\n // check if the operation objects are equivalent\n CHECK(op1 == op2);\n CHECK(op1 == op3);\n }\n\n SECTION(\"4.1 add\")\n {\n json const patch1 = R\"([{ \"op\": \"add\", \"path\": \"/a/b\", \"value\": [ \"foo\", \"bar\" ] }])\"_json;\n\n // However, the object itself or an array containing it does need\n // to exist, and it remains an error for that not to be the case.\n // For example, an \"add\" with a target location of \"/a/b\" starting\n // with this document\n json const doc1 = R\"({ \"a\": { \"foo\": 1 } })\"_json;\n\n // is not an error, because \"a\" exists, and \"b\" will be added to\n // its value.\n CHECK_NOTHROW(doc1.patch(patch1));\n auto doc1_ans = R\"(\n {\n \"a\": {\n \"foo\": 1,\n \"b\": [ \"foo\", \"bar\" ]\n }\n }\n )\"_json;\n CHECK(doc1.patch(patch1) == doc1_ans);\n\n // It is an error in this document:\n json const doc2 = R\"({ \"q\": { \"bar\": 2 } })\"_json;\n\n // because \"a\" does not exist.\n#if JSON_DIAGNOSTIC_POSITIONS\n CHECK_THROWS_WITH_AS(doc2.patch(patch1), \"[json.exception.out_of_range.403] (bytes 0-21) key 'a' not found\", json::out_of_range&);\n#else\n CHECK_THROWS_WITH_AS(doc2.patch(patch1), \"[json.exception.out_of_range.403] key 'a' not found\", json::out_of_range&);\n#endif\n\n json const doc3 = R\"({ \"a\": {} })\"_json;\n json const patch2 = R\"([{ \"op\": \"add\", \"path\": \"/a/b/c\", \"value\": 1 }])\"_json;\n\n // should cause an error because \"b\" does not exist in doc3\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(doc3.patch(patch2), \"[json.exception.out_of_range.403] (/a) key 'b' not found\", json::out_of_range&);\n#elif JSON_DIAGNOSTIC_POSITIONS\n CHECK_THROWS_WITH_AS(doc3.patch(patch2), \"[json.exception.out_of_range.403] (bytes 7-9) key 'b' not found\", json::out_of_range&);\n#else\n CHECK_THROWS_WITH_AS(doc3.patch(patch2), \"[json.exception.out_of_range.403] key 'b' not found\", json::out_of_range&);\n#endif\n }\n\n SECTION(\"4.2 remove\")\n {\n // If removing an element from an array, any elements above the\n // specified index are shifted one position to the left.\n json const doc = {1, 2, 3, 4};\n json const patch = {{{\"op\", \"remove\"}, {\"path\", \"/1\"}}};\n CHECK(doc.patch(patch) == json({1, 3, 4}));\n }\n\n SECTION(\"A.1. Adding an Object Member\")\n {\n // An example target JSON document:\n json const doc = R\"(\n { \"foo\": \"bar\"}\n )\"_json;\n\n // A JSON Patch document:\n json const patch = R\"(\n [\n { \"op\": \"add\", \"path\": \"/baz\", \"value\": \"qux\" }\n ]\n )\"_json;\n\n // The resulting JSON document:\n json expected = R\"(\n {\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n }\n )\"_json;\n\n // check if patched value is as expected\n CHECK(doc.patch(patch) == expected);\n\n // check roundtrip\n CHECK(doc.patch(json::diff(doc, expected)) == expected);\n }\n\n SECTION(\"A.2. Adding an Array Element\")\n {\n // An example target JSON document:\n json const doc = R\"(\n { \"foo\": [ \"bar\", \"baz\" ] }\n )\"_json;\n\n // A JSON Patch document:\n json const patch = R\"(\n [\n { \"op\": \"add\", \"path\": \"/foo/1\", \"value\": \"qux\" }\n ]\n )\"_json;\n\n // The resulting JSON document:\n json expected = R\"(\n { \"foo\": [ \"bar\", \"qux\", \"baz\" ] }\n )\"_json;\n\n // check if patched value is as expected\n CHECK(doc.patch(patch) == expected);\n\n // check roundtrip\n CHECK(doc.patch(json::diff(doc, expected)) == expected);\n }\n\n SECTION(\"A.3. Removing an Object Member\")\n {\n // An example target JSON document:\n json const doc = R\"(\n {\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n }\n )\"_json;\n\n // A JSON Patch document:\n json const patch = R\"(\n [\n { \"op\": \"remove\", \"path\": \"/baz\" }\n ]\n )\"_json;\n\n // The resulting JSON document:\n json expected = R\"(\n { \"foo\": \"bar\" }\n )\"_json;\n\n // check if patched value is as expected\n CHECK(doc.patch(patch) == expected);\n\n // check roundtrip\n CHECK(doc.patch(json::diff(doc, expected)) == expected);\n }\n\n SECTION(\"A.4. Removing an Array Element\")\n {\n // An example target JSON document:\n json const doc = R\"(\n { \"foo\": [ \"bar\", \"qux\", \"baz\" ] }\n )\"_json;\n\n // A JSON Patch document:\n json const patch = R\"(\n [\n { \"op\": \"remove\", \"path\": \"/foo/1\" }\n ]\n )\"_json;\n\n // The resulting JSON document:\n json expected = R\"(\n { \"foo\": [ \"bar\", \"baz\" ] }\n )\"_json;\n\n // check if patched value is as expected\n CHECK(doc.patch(patch) == expected);\n\n // check roundtrip\n CHECK(doc.patch(json::diff(doc, expected)) == expected);\n }\n\n SECTION(\"A.5. Replacing a Value\")\n {\n // An example target JSON document:\n json const doc = R\"(\n {\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n }\n )\"_json;\n\n // A JSON Patch document:\n json const patch = R\"(\n [\n { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" }\n ]\n )\"_json;\n\n json expected = R\"(\n {\n \"baz\": \"boo\",\n \"foo\": \"bar\"\n }\n )\"_json;\n\n // check if patched value is as expected\n CHECK(doc.patch(patch) == expected);\n\n // check roundtrip\n CHECK(doc.patch(json::diff(doc, expected)) == expected);\n }\n\n SECTION(\"A.6. Moving a Value\")\n {\n // An example target JSON document:\n json const doc = R\"(\n {\n \"foo\": {\n \"bar\": \"baz\",\n \"waldo\": \"fred\"\n },\n \"qux\": {\n \"corge\": \"grault\"\n }\n }\n )\"_json;\n\n // A JSON Patch document:\n json const patch = R\"(\n [\n { \"op\": \"move\", \"from\": \"/foo/waldo\", \"path\": \"/qux/thud\" }\n ]\n )\"_json;\n\n // The resulting JSON document:\n json expected = R\"(\n {\n \"foo\": {\n \"bar\": \"baz\"\n },\n \"qux\": {\n \"corge\": \"grault\",\n \"thud\": \"fred\"\n }\n }\n )\"_json;\n\n // check if patched value is as expected\n CHECK(doc.patch(patch) == expected);\n\n // check roundtrip\n CHECK(doc.patch(json::diff(doc, expected)) == expected);\n }\n\n SECTION(\"A.7. Moving a Value\")\n {\n // An example target JSON document:\n json const doc = R\"(\n { \"foo\": [ \"all\", \"grass\", \"cows\", \"eat\" ] }\n )\"_json;\n\n // A JSON Patch document:\n json const patch = R\"(\n [\n { \"op\": \"move\", \"from\": \"/foo/1\", \"path\": \"/foo/3\" }\n ]\n )\"_json;\n\n // The resulting JSON document:\n json expected = R\"(\n { \"foo\": [ \"all\", \"cows\", \"eat\", \"grass\" ] }\n )\"_json;\n\n // check if patched value is as expected\n CHECK(doc.patch(patch) == expected);\n\n // check roundtrip\n CHECK(doc.patch(json::diff(doc, expected)) == expected);\n }\n\n SECTION(\"A.8. Testing a Value: Success\")\n {\n // An example target JSON document:\n json doc = R\"(\n {\n \"baz\": \"qux\",\n \"foo\": [ \"a\", 2, \"c\" ]\n }\n )\"_json;\n\n // A JSON Patch document that will result in successful evaluation:\n json const patch = R\"(\n [\n { \"op\": \"test\", \"path\": \"/baz\", \"value\": \"qux\" },\n { \"op\": \"test\", \"path\": \"/foo/1\", \"value\": 2 }\n ]\n )\"_json;\n\n // check if evaluation does not throw\n CHECK_NOTHROW(doc.patch(patch));\n // check if patched document is unchanged\n CHECK(doc.patch(patch) == doc);\n }\n\n SECTION(\"A.9. Testing a Value: Error\")\n {\n // An example target JSON document:\n json const doc = R\"(\n { \"baz\": \"qux\" }\n )\"_json;\n\n // A JSON Patch document that will result in an error condition:\n json patch = R\"(\n [\n { \"op\": \"test\", \"path\": \"/baz\", \"value\": \"bar\" }\n ]\n )\"_json;\n\n // check that evaluation throws\n CHECK_THROWS_AS(doc.patch(patch), json::other_error&);\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_STD_STR(doc.patch(patch), \"[json.exception.other_error.501] (/0) unsuccessful: \" + patch[0].dump());\n#elif JSON_DIAGNOSTIC_POSITIONS\n CHECK_THROWS_WITH_STD_STR(doc.patch(patch), \"[json.exception.other_error.501] (bytes 47-95) unsuccessful: \" + patch[0].dump());\n#else\n CHECK_THROWS_WITH_STD_STR(doc.patch(patch), \"[json.exception.other_error.501] unsuccessful: \" + patch[0].dump());\n#endif\n }\n\n SECTION(\"A.10. Adding a Nested Member Object\")\n {\n // An example target JSON document:\n json const doc = R\"(\n { \"foo\": \"bar\" }\n )\"_json;\n\n // A JSON Patch document:\n json const patch = R\"(\n [\n { \"op\": \"add\", \"path\": \"/child\", \"value\": { \"grandchild\": { } } }\n ]\n )\"_json;\n\n // The resulting JSON document:\n json expected = R\"(\n {\n \"foo\": \"bar\",\n \"child\": {\n \"grandchild\": {\n }\n }\n }\n )\"_json;\n\n // check if patched value is as expected\n CHECK(doc.patch(patch) == expected);\n\n // check roundtrip\n CHECK(doc.patch(json::diff(doc, expected)) == expected);\n }\n\n SECTION(\"A.11. Ignoring Unrecognized Elements\")\n {\n // An example target JSON document:\n json const doc = R\"(\n { \"foo\": \"bar\" }\n )\"_json;\n\n // A JSON Patch document:\n json const patch = R\"(\n [\n { \"op\": \"add\", \"path\": \"/baz\", \"value\": \"qux\", \"xyz\": 123 }\n ]\n )\"_json;\n\n json expected = R\"(\n {\n \"foo\": \"bar\",\n \"baz\": \"qux\"\n } \n )\"_json;\n\n // check if patched value is as expected\n CHECK(doc.patch(patch) == expected);\n\n // check roundtrip\n CHECK(doc.patch(json::diff(doc, expected)) == expected);\n }\n\n SECTION(\"A.12. Adding to a Nonexistent Target\")\n {\n // An example target JSON document:\n json const doc = R\"(\n { \"foo\": \"bar\" }\n )\"_json;\n\n // A JSON Patch document:\n json const patch = R\"(\n [\n { \"op\": \"add\", \"path\": \"/baz/bat\", \"value\": \"qux\" }\n ]\n )\"_json;\n\n // This JSON Patch document, applied to the target JSON document\n // above, would result in an error (therefore, it would not be\n // applied), because the \"add\" operation's target location that\n // references neither the root of the document, nor a member of\n // an existing object, nor a member of an existing array.\n#if JSON_DIAGNOSTIC_POSITIONS\n CHECK_THROWS_WITH_AS(doc.patch(patch), \"[json.exception.out_of_range.403] (bytes 21-37) key 'baz' not found\", json::out_of_range&);\n#else\n CHECK_THROWS_WITH_AS(doc.patch(patch), \"[json.exception.out_of_range.403] key 'baz' not found\", json::out_of_range&);\n#endif\n }\n\n // A.13. Invalid JSON Patch Document\n // not applicable\n\n SECTION(\"A.14. Escape Ordering\")\n {\n // An example target JSON document:\n json const doc = R\"(\n {\n \"/\": 9,\n \"~1\": 10\n }\n )\"_json;\n\n // A JSON Patch document:\n json const patch = R\"(\n [\n {\"op\": \"test\", \"path\": \"/~01\", \"value\": 10}\n ]\n )\"_json;\n\n json expected = R\"(\n {\n \"/\": 9,\n \"~1\": 10\n } \n )\"_json;\n\n // check if patched value is as expected\n CHECK(doc.patch(patch) == expected);\n\n // check roundtrip\n CHECK(doc.patch(json::diff(doc, expected)) == expected);\n }\n\n SECTION(\"A.15. Comparing Strings and Numbers\")\n {\n // An example target JSON document:\n json const doc = R\"(\n {\n \"/\": 9,\n \"~1\": 10\n } \n )\"_json;\n\n // A JSON Patch document that will result in an error condition:\n json patch = R\"(\n [\n {\"op\": \"test\", \"path\": \"/~01\", \"value\": \"10\"}\n ]\n )\"_json;\n\n // check that evaluation throws\n CHECK_THROWS_AS(doc.patch(patch), json::other_error&);\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_STD_STR(doc.patch(patch), \"[json.exception.other_error.501] (/0) unsuccessful: \" + patch[0].dump());\n#elif JSON_DIAGNOSTIC_POSITIONS\n CHECK_THROWS_WITH_STD_STR(doc.patch(patch), \"[json.exception.other_error.501] (bytes 47-92) unsuccessful: \" + patch[0].dump());\n#else\n CHECK_THROWS_WITH_STD_STR(doc.patch(patch), \"[json.exception.other_error.501] unsuccessful: \" + patch[0].dump());\n#endif\n }\n\n SECTION(\"A.16. Adding an Array Value\")\n {\n // An example target JSON document:\n json const doc = R\"(\n { \"foo\": [\"bar\"] }\n )\"_json;\n\n // A JSON Patch document:\n json const patch = R\"(\n [\n { \"op\": \"add\", \"path\": \"/foo/-\", \"value\": [\"abc\", \"def\"] }\n ]\n )\"_json;\n\n // The resulting JSON document:\n json expected = R\"(\n { \"foo\": [\"bar\", [\"abc\", \"def\"]] }\n )\"_json;\n\n // check if patched value is as expected\n CHECK(doc.patch(patch) == expected);\n\n // check roundtrip\n CHECK(doc.patch(json::diff(doc, expected)) == expected);\n }\n }\n\n SECTION(\"own examples\")\n {\n SECTION(\"add\")\n {\n SECTION(\"add to the root element\")\n {\n // If the path is the root of the target document - the\n // specified value becomes the entire content of the target\n // document.\n\n // An example target JSON document:\n json const doc = 17;\n\n // A JSON Patch document:\n json const patch = R\"(\n [\n { \"op\": \"add\", \"path\": \"\", \"value\": [1,2,3] }\n ]\n )\"_json;\n\n // The resulting JSON document:\n json expected = {1, 2, 3};\n\n // check if patched value is as expected\n CHECK(doc.patch(patch) == expected);\n\n // check roundtrip\n CHECK(doc.patch(json::diff(doc, expected)) == expected);\n }\n\n SECTION(\"add to end of the array\")\n {\n // The specified index MUST NOT be greater than the number of\n // elements in the array. The example below uses and index of\n // exactly the number of elements in the array which is legal.\n\n // An example target JSON document:\n json const doc = {0, 1, 2};\n\n // A JSON Patch document:\n json const patch = R\"(\n [\n { \"op\": \"add\", \"path\": \"/3\", \"value\": 3 }\n ]\n )\"_json;\n\n // The resulting JSON document:\n json expected = {0, 1, 2, 3};\n\n // check if patched value is as expected\n CHECK(doc.patch(patch) == expected);\n\n // check roundtrip\n CHECK(doc.patch(json::diff(doc, expected)) == expected);\n }\n }\n\n SECTION(\"copy\")\n {\n // An example target JSON document:\n json const doc = R\"(\n {\n \"foo\": {\n \"bar\": \"baz\",\n \"waldo\": \"fred\"\n },\n \"qux\": {\n \"corge\": \"grault\"\n }\n }\n )\"_json;\n\n // A JSON Patch document:\n json const patch = R\"(\n [\n { \"op\": \"copy\", \"from\": \"/foo/waldo\", \"path\": \"/qux/thud\" }\n ]\n )\"_json;\n\n // The resulting JSON document:\n json expected = R\"(\n {\n \"foo\": {\n \"bar\": \"baz\",\n \"waldo\": \"fred\"\n },\n \"qux\": {\n \"corge\": \"grault\",\n \"thud\": \"fred\"\n }\n }\n )\"_json;\n\n // check if patched value is as expected\n CHECK(doc.patch(patch) == expected);\n\n // check roundtrip\n CHECK(doc.patch(json::diff(doc, expected)) == expected);\n }\n\n SECTION(\"replace\")\n {\n json const j = \"string\";\n json const patch = {{{\"op\", \"replace\"}, {\"path\", \"\"}, {\"value\", 1}}};\n CHECK(j.patch(patch) == json(1));\n }\n\n SECTION(\"documentation GIF\")\n {\n {\n // a JSON patch\n json const p1 = R\"(\n [{\"op\": \"add\", \"path\": \"/GB\", \"value\": \"London\"}]\n )\"_json;\n\n // a JSON value\n json const source = R\"(\n {\"D\": \"Berlin\", \"F\": \"Paris\"}\n )\"_json;\n\n // apply the patch\n const json target = source.patch(p1);\n // target = { \"D\": \"Berlin\", \"F\": \"Paris\", \"GB\": \"London\" }\n CHECK(target == R\"({ \"D\": \"Berlin\", \"F\": \"Paris\", \"GB\": \"London\" })\"_json);\n\n // create a diff from two JSONs\n const json p2 = json::diff(target, source); // NOLINT(readability-suspicious-call-argument)\n // p2 = [{\"op\": \"delete\", \"path\": \"/GB\"}]\n CHECK(p2 == R\"([{\"op\":\"remove\",\"path\":\"/GB\"}])\"_json);\n }\n {\n // a JSON value\n json j = {\"good\", \"bad\", \"ugly\"};\n\n // a JSON pointer\n auto ptr = json::json_pointer(\"/2\");\n\n // use to access elements\n j[ptr] = {{\"it\", \"cattivo\"}};\n CHECK(j == R\"([\"good\",\"bad\",{\"it\":\"cattivo\"}])\"_json);\n\n // use user-defined string literal\n j[\"/2/en\"_json_pointer] = \"ugly\";\n CHECK(j == R\"([\"good\",\"bad\",{\"en\":\"ugly\",\"it\":\"cattivo\"}])\"_json);\n\n const json flat = j.flatten();\n CHECK(flat == R\"({\"/0\":\"good\",\"/1\":\"bad\",\"/2/en\":\"ugly\",\"/2/it\":\"cattivo\"})\"_json);\n }\n }\n }\n\n SECTION(\"errors\")\n {\n SECTION(\"unknown operation\")\n {\n SECTION(\"not an array\")\n {\n json const j;\n json const patch = {{\"op\", \"add\"}, {\"path\", \"\"}, {\"value\", 1}};\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.104] parse error: JSON patch must be an array of objects\", json::parse_error&);\n }\n\n SECTION(\"not an array of objects\")\n {\n json const j;\n json const patch = {\"op\", \"add\", \"path\", \"\", \"value\", 1};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.104] parse error: (/0) JSON patch must be an array of objects\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.104] parse error: JSON patch must be an array of objects\", json::parse_error&);\n#endif\n }\n\n SECTION(\"missing 'op'\")\n {\n json const j;\n json const patch = {{{\"foo\", \"bar\"}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation must have member 'op'\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation must have member 'op'\", json::parse_error&);\n#endif\n }\n\n SECTION(\"non-string 'op'\")\n {\n json const j;\n json const patch = {{{\"op\", 1}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation must have string member 'op'\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation must have string member 'op'\", json::parse_error&);\n#endif\n }\n\n SECTION(\"invalid operation\")\n {\n json const j;\n json const patch = {{{\"op\", \"foo\"}, {\"path\", \"\"}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation value 'foo' is invalid\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation value 'foo' is invalid\", json::parse_error&);\n#endif\n }\n }\n\n SECTION(\"add\")\n {\n SECTION(\"missing 'path'\")\n {\n json const j;\n json const patch = {{{\"op\", \"add\"}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation 'add' must have member 'path'\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation 'add' must have member 'path'\", json::parse_error&);\n#endif\n }\n\n SECTION(\"non-string 'path'\")\n {\n json const j;\n json const patch = {{{\"op\", \"add\"}, {\"path\", 1}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation 'add' must have string member 'path'\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation 'add' must have string member 'path'\", json::parse_error&);\n#endif\n }\n\n SECTION(\"missing 'value'\")\n {\n json const j;\n json const patch = {{{\"op\", \"add\"}, {\"path\", \"\"}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation 'add' must have member 'value'\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation 'add' must have member 'value'\", json::parse_error&);\n#endif\n }\n\n SECTION(\"invalid array index\")\n {\n json const j = {1, 2};\n json const patch = {{{\"op\", \"add\"}, {\"path\", \"/4\"}, {\"value\", 4}}};\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.out_of_range.401] array index 4 is out of range\", json::out_of_range&);\n }\n }\n\n SECTION(\"remove\")\n {\n SECTION(\"missing 'path'\")\n {\n json const j;\n json const patch = {{{\"op\", \"remove\"}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation 'remove' must have member 'path'\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation 'remove' must have member 'path'\", json::parse_error&);\n#endif\n }\n\n SECTION(\"non-string 'path'\")\n {\n json const j;\n json const patch = {{{\"op\", \"remove\"}, {\"path\", 1}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation 'remove' must have string member 'path'\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation 'remove' must have string member 'path'\", json::parse_error&);\n#endif\n }\n\n SECTION(\"nonexisting target location (array)\")\n {\n json const j = {1, 2, 3};\n json const patch = {{{\"op\", \"remove\"}, {\"path\", \"/17\"}}};\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.out_of_range.401] array index 17 is out of range\", json::out_of_range&);\n }\n\n SECTION(\"nonexisting target location (object)\")\n {\n json const j = {{\"foo\", 1}, {\"bar\", 2}};\n json const patch = {{{\"op\", \"remove\"}, {\"path\", \"/baz\"}}};\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.out_of_range.403] key 'baz' not found\", json::out_of_range&);\n }\n\n SECTION(\"root element as target location\")\n {\n json const j = \"string\";\n json const patch = {{{\"op\", \"remove\"}, {\"path\", \"\"}}};\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.out_of_range.405] JSON pointer has no parent\", json::out_of_range&);\n }\n }\n\n SECTION(\"replace\")\n {\n SECTION(\"missing 'path'\")\n {\n json const j;\n json const patch = {{{\"op\", \"replace\"}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation 'replace' must have member 'path'\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation 'replace' must have member 'path'\", json::parse_error&);\n#endif\n }\n\n SECTION(\"non-string 'path'\")\n {\n json const j;\n json const patch = {{{\"op\", \"replace\"}, {\"path\", 1}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation 'replace' must have string member 'path'\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation 'replace' must have string member 'path'\", json::parse_error&);\n#endif\n }\n\n SECTION(\"missing 'value'\")\n {\n json const j;\n json const patch = {{{\"op\", \"replace\"}, {\"path\", \"\"}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation 'replace' must have member 'value'\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation 'replace' must have member 'value'\", json::parse_error&);\n#endif\n }\n\n SECTION(\"nonexisting target location (array)\")\n {\n json const j = {1, 2, 3};\n json const patch = {{{\"op\", \"replace\"}, {\"path\", \"/17\"}, {\"value\", 19}}};\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.out_of_range.401] array index 17 is out of range\", json::out_of_range&);\n }\n\n SECTION(\"nonexisting target location (object)\")\n {\n json const j = {{\"foo\", 1}, {\"bar\", 2}};\n json const patch = {{{\"op\", \"replace\"}, {\"path\", \"/baz\"}, {\"value\", 3}}};\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.out_of_range.403] key 'baz' not found\", json::out_of_range&);\n }\n }\n\n SECTION(\"move\")\n {\n SECTION(\"missing 'path'\")\n {\n json const j;\n json const patch = {{{\"op\", \"move\"}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation 'move' must have member 'path'\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation 'move' must have member 'path'\", json::parse_error&);\n#endif\n }\n\n SECTION(\"non-string 'path'\")\n {\n json const j;\n json const patch = {{{\"op\", \"move\"}, {\"path\", 1}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation 'move' must have string member 'path'\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation 'move' must have string member 'path'\", json::parse_error&);\n#endif\n }\n\n SECTION(\"missing 'from'\")\n {\n json const j;\n json const patch = {{{\"op\", \"move\"}, {\"path\", \"\"}}};\n CHECK_THROWS_AS(j.patch(patch), json::parse_error&);\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation 'move' must have member 'from'\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation 'move' must have member 'from'\", json::parse_error&);\n#endif\n }\n\n SECTION(\"non-string 'from'\")\n {\n json const j;\n json const patch = {{{\"op\", \"move\"}, {\"path\", \"\"}, {\"from\", 1}}};\n CHECK_THROWS_AS(j.patch(patch), json::parse_error&);\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation 'move' must have string member 'from'\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation 'move' must have string member 'from'\", json::parse_error&);\n#endif\n }\n\n SECTION(\"nonexisting from location (array)\")\n {\n json const j = {1, 2, 3};\n json const patch = {{{\"op\", \"move\"}, {\"path\", \"/0\"}, {\"from\", \"/5\"}}};\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.out_of_range.401] array index 5 is out of range\", json::out_of_range&);\n }\n\n SECTION(\"nonexisting from location (object)\")\n {\n json const j = {{\"foo\", 1}, {\"bar\", 2}};\n json const patch = {{{\"op\", \"move\"}, {\"path\", \"/baz\"}, {\"from\", \"/baz\"}}};\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.out_of_range.403] key 'baz' not found\", json::out_of_range&);\n }\n }\n\n SECTION(\"copy\")\n {\n SECTION(\"missing 'path'\")\n {\n json const j;\n json const patch = {{{\"op\", \"copy\"}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation 'copy' must have member 'path'\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation 'copy' must have member 'path'\", json::parse_error&);\n#endif\n }\n\n SECTION(\"non-string 'path'\")\n {\n json const j;\n json const patch = {{{\"op\", \"copy\"}, {\"path\", 1}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation 'copy' must have string member 'path'\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation 'copy' must have string member 'path'\", json::parse_error&);\n#endif\n }\n\n SECTION(\"missing 'from'\")\n {\n json const j;\n json const patch = {{{\"op\", \"copy\"}, {\"path\", \"\"}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation 'copy' must have member 'from'\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation 'copy' must have member 'from'\", json::parse_error&);\n#endif\n }\n\n SECTION(\"non-string 'from'\")\n {\n json const j;\n json const patch = {{{\"op\", \"copy\"}, {\"path\", \"\"}, {\"from\", 1}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation 'copy' must have string member 'from'\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation 'copy' must have string member 'from'\", json::parse_error&);\n#endif\n }\n\n SECTION(\"nonexisting from location (array)\")\n {\n json const j = {1, 2, 3};\n json const patch = {{{\"op\", \"copy\"}, {\"path\", \"/0\"}, {\"from\", \"/5\"}}};\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.out_of_range.401] array index 5 is out of range\", json::out_of_range&);\n }\n\n SECTION(\"nonexisting from location (object)\")\n {\n json const j = {{\"foo\", 1}, {\"bar\", 2}};\n json const patch = {{{\"op\", \"copy\"}, {\"path\", \"/fob\"}, {\"from\", \"/baz\"}}};\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.out_of_range.403] key 'baz' not found\", json::out_of_range&);\n }\n }\n\n SECTION(\"test\")\n {\n SECTION(\"missing 'path'\")\n {\n json const j;\n json const patch = {{{\"op\", \"test\"}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation 'test' must have member 'path'\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation 'test' must have member 'path'\", json::parse_error&);\n#endif\n }\n\n SECTION(\"non-string 'path'\")\n {\n json const j;\n json const patch = {{{\"op\", \"test\"}, {\"path\", 1}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation 'test' must have string member 'path'\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation 'test' must have string member 'path'\", json::parse_error&);\n#endif\n }\n\n SECTION(\"missing 'value'\")\n {\n json const j;\n json const patch = {{{\"op\", \"test\"}, {\"path\", \"\"}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: (/0) operation 'test' must have member 'value'\", json::parse_error&);\n#else\n CHECK_THROWS_WITH_AS(j.patch(patch), \"[json.exception.parse_error.105] parse error: operation 'test' must have member 'value'\", json::parse_error&);\n#endif\n }\n }\n }\n\n SECTION(\"Examples from jsonpatch.com\")\n {\n SECTION(\"Simple Example\")\n {\n // The original document\n json const doc = R\"(\n {\n \"baz\": \"qux\",\n \"foo\": \"bar\"\n }\n )\"_json;\n\n // The patch\n json const patch = R\"(\n [\n { \"op\": \"replace\", \"path\": \"/baz\", \"value\": \"boo\" },\n { \"op\": \"add\", \"path\": \"/hello\", \"value\": [\"world\"] },\n { \"op\": \"remove\", \"path\": \"/foo\"}\n ]\n )\"_json;\n\n // The result\n json result = R\"(\n {\n \"baz\": \"boo\",\n \"hello\": [\"world\"]\n }\n )\"_json;\n\n // check if patched value is as expected\n CHECK(doc.patch(patch) == result);\n\n // check roundtrip\n CHECK(doc.patch(json::diff(doc, result)) == result);\n }\n\n SECTION(\"Operations\")\n {\n // The original document\n json const doc = R\"(\n {\n \"biscuits\": [\n {\"name\":\"Digestive\"},\n {\"name\": \"Choco Liebniz\"}\n ]\n }\n )\"_json;\n\n SECTION(\"add\")\n {\n // The patch\n json const patch = R\"(\n [\n {\"op\": \"add\", \"path\": \"/biscuits/1\", \"value\": {\"name\": \"Ginger Nut\"}}\n ]\n )\"_json;\n\n // The result\n json result = R\"(\n {\n \"biscuits\": [\n {\"name\": \"Digestive\"},\n {\"name\": \"Ginger Nut\"},\n {\"name\": \"Choco Liebniz\"}\n ]\n }\n )\"_json;\n\n // check if patched value is as expected\n CHECK(doc.patch(patch) == result);\n\n // check roundtrip\n CHECK(doc.patch(json::diff(doc, result)) == result);\n }\n\n SECTION(\"remove\")\n {\n // The patch\n json const patch = R\"(\n [\n {\"op\": \"remove\", \"path\": \"/biscuits\"}\n ]\n )\"_json;\n\n // The result\n json result = R\"(\n {}\n )\"_json;\n\n // check if patched value is as expected\n CHECK(doc.patch(patch) == result);\n\n // check roundtrip\n CHECK(doc.patch(json::diff(doc, result)) == result);\n }\n\n SECTION(\"replace\")\n {\n // The patch\n json const patch = R\"(\n [\n {\"op\": \"replace\", \"path\": \"/biscuits/0/name\", \"value\": \"Chocolate Digestive\"}\n ]\n )\"_json;\n\n // The result\n json result = R\"(\n {\n \"biscuits\": [\n {\"name\": \"Chocolate Digestive\"},\n {\"name\": \"Choco Liebniz\"}\n ]\n }\n )\"_json;\n\n // check if patched value is as expected\n CHECK(doc.patch(patch) == result);\n\n // check roundtrip\n CHECK(doc.patch(json::diff(doc, result)) == result);\n }\n\n SECTION(\"copy\")\n {\n // The patch\n json const patch = R\"(\n [\n {\"op\": \"copy\", \"from\": \"/biscuits/0\", \"path\": \"/best_biscuit\"}\n ]\n )\"_json;\n\n // The result\n json result = R\"(\n {\n \"biscuits\": [\n {\"name\": \"Digestive\"},\n {\"name\": \"Choco Liebniz\"}\n ],\n \"best_biscuit\": {\n \"name\": \"Digestive\"\n }\n }\n )\"_json;\n\n // check if patched value is as expected\n CHECK(doc.patch(patch) == result);\n\n // check roundtrip\n CHECK(doc.patch(json::diff(doc, result)) == result);\n }\n\n SECTION(\"move\")\n {\n // The patch\n json const patch = R\"(\n [\n {\"op\": \"move\", \"from\": \"/biscuits\", \"path\": \"/cookies\"}\n ]\n )\"_json;\n\n // The result\n json result = R\"(\n {\n \"cookies\": [\n {\"name\": \"Digestive\"},\n {\"name\": \"Choco Liebniz\"}\n ]\n }\n )\"_json;\n\n // check if patched value is as expected\n CHECK(doc.patch(patch) == result);\n\n // check roundtrip\n CHECK(doc.patch(json::diff(doc, result)) == result);\n }\n\n SECTION(\"test\")\n {\n // The patch\n json patch = R\"(\n [\n {\"op\": \"test\", \"path\": \"/best_biscuit/name\", \"value\": \"Choco Liebniz\"}\n ]\n )\"_json;\n\n // the test will fail\n CHECK_THROWS_AS(doc.patch(patch), json::other_error&);\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_STD_STR(doc.patch(patch), \"[json.exception.other_error.501] (/0) unsuccessful: \" + patch[0].dump());\n#elif JSON_DIAGNOSTIC_POSITIONS\n CHECK_THROWS_WITH_STD_STR(doc.patch(patch), \"[json.exception.other_error.501] (bytes 47-117) unsuccessful: \" + patch[0].dump());\n#else\n CHECK_THROWS_WITH_STD_STR(doc.patch(patch), \"[json.exception.other_error.501] unsuccessful: \" + patch[0].dump());\n#endif\n }\n }\n }\n\n SECTION(\"Examples from bruth.github.io/jsonpatch-js\")\n {\n SECTION(\"add\")\n {\n CHECK(R\"( {} )\"_json.patch(\n R\"( [{\"op\": \"add\", \"path\": \"/foo\", \"value\": \"bar\"}] )\"_json\n ) == R\"( {\"foo\": \"bar\"} )\"_json);\n\n CHECK(R\"( {\"foo\": [1, 3]} )\"_json.patch(\n R\"( [{\"op\": \"add\", \"path\": \"/foo\", \"value\": \"bar\"}] )\"_json\n ) == R\"( {\"foo\": \"bar\"} )\"_json);\n\n CHECK(R\"( {\"foo\": [{}]} )\"_json.patch(\n R\"( [{\"op\": \"add\", \"path\": \"/foo/0/bar\", \"value\": \"baz\"}] )\"_json\n ) == R\"( {\"foo\": [{\"bar\": \"baz\"}]} )\"_json);\n }\n\n SECTION(\"remove\")\n {\n CHECK(R\"( {\"foo\": \"bar\"} )\"_json.patch(\n R\"( [{\"op\": \"remove\", \"path\": \"/foo\"}] )\"_json\n ) == R\"( {} )\"_json);\n\n CHECK(R\"( {\"foo\": [1, 2, 3]} )\"_json.patch(\n R\"( [{\"op\": \"remove\", \"path\": \"/foo/1\"}] )\"_json\n ) == R\"( {\"foo\": [1, 3]} )\"_json);\n\n CHECK(R\"( {\"foo\": [{\"bar\": \"baz\"}]} )\"_json.patch(\n R\"( [{\"op\": \"remove\", \"path\": \"/foo/0/bar\"}] )\"_json\n ) == R\"( {\"foo\": [{}]} )\"_json);\n }\n\n SECTION(\"replace\")\n {\n CHECK(R\"( {\"foo\": \"bar\"} )\"_json.patch(\n R\"( [{\"op\": \"replace\", \"path\": \"/foo\", \"value\": 1}] )\"_json\n ) == R\"( {\"foo\": 1} )\"_json);\n\n CHECK(R\"( {\"foo\": [1, 2, 3]} )\"_json.patch(\n R\"( [{\"op\": \"replace\", \"path\": \"/foo/1\", \"value\": 4}] )\"_json\n ) == R\"( {\"foo\": [1, 4, 3]} )\"_json);\n\n CHECK(R\"( {\"foo\": [{\"bar\": \"baz\"}]} )\"_json.patch(\n R\"( [{\"op\": \"replace\", \"path\": \"/foo/0/bar\", \"value\": 1}] )\"_json\n ) == R\"( {\"foo\": [{\"bar\": 1}]} )\"_json);\n }\n\n SECTION(\"move\")\n {\n CHECK(R\"( {\"foo\": [1, 2, 3]} )\"_json.patch(\n R\"( [{\"op\": \"move\", \"from\": \"/foo\", \"path\": \"/bar\"}] )\"_json\n ) == R\"( {\"bar\": [1, 2, 3]} )\"_json);\n }\n\n SECTION(\"copy\")\n {\n CHECK(R\"( {\"foo\": [1, 2, 3]} )\"_json.patch(\n R\"( [{\"op\": \"copy\", \"from\": \"/foo/1\", \"path\": \"/bar\"}] )\"_json\n ) == R\"( {\"foo\": [1, 2, 3], \"bar\": 2} )\"_json);\n }\n\n SECTION(\"copy\")\n {\n CHECK_NOTHROW(R\"( {\"foo\": \"bar\"} )\"_json.patch(\n R\"( [{\"op\": \"test\", \"path\": \"/foo\", \"value\": \"bar\"}] )\"_json));\n }\n }\n\n SECTION(\"Tests from github.com/json-patch/json-patch-tests\")\n {\n for (const auto* filename :\n {\n TEST_DATA_DIRECTORY \"/json-patch-tests/spec_tests.json\",\n TEST_DATA_DIRECTORY \"/json-patch-tests/tests.json\"\n })\n {\n CAPTURE(filename)\n std::ifstream f(filename);\n json const suite = json::parse(f);\n\n for (const auto& test : suite)\n {\n INFO_WITH_TEMP(test.value(\"comment\", \"\"));\n\n // skip tests marked as disabled\n if (test.value(\"disabled\", false))\n {\n continue;\n }\n\n const auto& doc = test[\"doc\"];\n const auto& patch = test[\"patch\"];\n\n if (test.count(\"error\") == 0) // NOLINT(readability-container-contains)\n {\n // if an expected value is given, use it; use doc otherwise\n const auto& expected = test.value(\"expected\", doc);\n CHECK(doc.patch(patch) == expected);\n }\n else\n {\n CHECK_THROWS(doc.patch(patch));\n }\n }\n }\n }\n}\n\nTEST_CASE(\"JSON patch - add to a primitive parent (regression #4292)\")\n{\n // Regression test for https://github.com/nlohmann/json/issues/4292\n //\n // An \"add\" operation whose parent location resolves to a primitive\n // (non-container) value must be rejected with a catchable exception.\n // Previously this hit JSON_ASSERT(false) in operation_add, which aborts\n // the process in debug builds and silently dropped the operation (leaving\n // a wrong result) when assertions were compiled out (NDEBUG). It now\n // throws out_of_range.411.\n //\n // The documents below are constructed programmatically (not parsed) so\n // they carry no byte positions; the JSON_DIAGNOSTICS path prefix is\n // handled by the guards. The exact message with positions is covered in\n // unit-diagnostic-positions.cpp.\n\n SECTION(\"string parent\")\n {\n json const doc = {{\"foo\", {{\"bar\", \"a string\"}}}};\n json const patch = {{{\"op\", \"add\"}, {\"path\", \"/foo/bar/baz\"}, {\"value\", 1}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(doc.patch(patch), \"[json.exception.out_of_range.411] (/foo/bar) cannot add value: the JSON Patch 'add' target's parent is of type string, but must be an object or array\", json::out_of_range&);\n#else\n CHECK_THROWS_WITH_AS(doc.patch(patch), \"[json.exception.out_of_range.411] cannot add value: the JSON Patch 'add' target's parent is of type string, but must be an object or array\", json::out_of_range&);\n#endif\n }\n\n SECTION(\"number parent\")\n {\n json const doc = {{\"foo\", 1}};\n json const patch = {{{\"op\", \"add\"}, {\"path\", \"/foo/bar\"}, {\"value\", 2}}};\n#if JSON_DIAGNOSTICS\n CHECK_THROWS_WITH_AS(doc.patch(patch), \"[json.exception.out_of_range.411] (/foo) cannot add value: the JSON Patch 'add' target's parent is of type number, but must be an object or array\", json::out_of_range&);\n#else\n CHECK_THROWS_WITH_AS(doc.patch(patch), \"[json.exception.out_of_range.411] cannot add value: the JSON Patch 'add' target's parent is of type number, but must be an object or array\", json::out_of_range&);\n#endif\n }\n\n SECTION(\"original two-step sequence from the issue\")\n {\n // The user's two-step patch from #4292: first turn /xyz/1 into a\n // string, then try to add a member inside that string.\n json const doc = R\"( { \"xyz\": [ { \"lmn\": \"214\", \"nnp\": \"001\" } ] } )\"_json;\n json const patch = R\"(\n [\n { \"op\": \"add\", \"path\": \"/xyz/1\", \"value\": \"\" },\n { \"op\": \"add\", \"path\": \"/xyz/1/lmn\", \"value\": \"214\" }\n ]\n )\"_json;\n\n CHECK_THROWS_AS(doc.patch(patch), json::out_of_range&);\n }\n}", "messages": null, "tools": null} {"id": "6ce3fe949a64b60d", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "include/nlohmann/detail/input/json_sax.hpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 32650, "sha256": "ac6a0fc943cf3708dae2adc6a796947beab5a3fdf5129f4fff148ce99f2c07a7", "text": "// __ _____ _____ _____\n// __| | __| | | | JSON for Modern C++\n// | | |__ | | | | | | version 3.12.0\n// |_____|_____|_____|_|___| https://github.com/nlohmann/json\n//\n// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann \n// SPDX-License-Identifier: MIT\n\n#pragma once\n\n#include \n#include // string\n#include // enable_if_t\n#include // move\n#include // vector\n\n#include \n#include \n#include \n#include \nNLOHMANN_JSON_NAMESPACE_BEGIN\n\n/*!\n@brief SAX interface\n\nThis class describes the SAX interface used by @ref nlohmann::json::sax_parse.\nEach function is called in different situations while the input is parsed. The\nboolean return value informs the parser whether to continue processing the\ninput.\n*/\ntemplate\nstruct json_sax\n{\n using number_integer_t = typename BasicJsonType::number_integer_t;\n using number_unsigned_t = typename BasicJsonType::number_unsigned_t;\n using number_float_t = typename BasicJsonType::number_float_t;\n using string_t = typename BasicJsonType::string_t;\n using binary_t = typename BasicJsonType::binary_t;\n\n /*!\n @brief a null value was read\n @return whether parsing should proceed\n */\n virtual bool null() = 0;\n\n /*!\n @brief a boolean value was read\n @param[in] val boolean value\n @return whether parsing should proceed\n */\n virtual bool boolean(bool val) = 0;\n\n /*!\n @brief an integer number was read\n @param[in] val integer value\n @return whether parsing should proceed\n */\n virtual bool number_integer(number_integer_t val) = 0;\n\n /*!\n @brief an unsigned integer number was read\n @param[in] val unsigned integer value\n @return whether parsing should proceed\n */\n virtual bool number_unsigned(number_unsigned_t val) = 0;\n\n /*!\n @brief a floating-point number was read\n @param[in] val floating-point value\n @param[in] s raw token value\n @return whether parsing should proceed\n */\n virtual bool number_float(number_float_t val, const string_t& s) = 0;\n\n /*!\n @brief a string value was read\n @param[in] val string value\n @return whether parsing should proceed\n @note It is safe to move the passed string value.\n */\n virtual bool string(string_t& val) = 0;\n\n /*!\n @brief a binary value was read\n @param[in] val binary value\n @return whether parsing should proceed\n @note It is safe to move the passed binary value.\n */\n virtual bool binary(binary_t& val) = 0;\n\n /*!\n @brief the beginning of an object was read\n @param[in] elements number of object elements or -1 if unknown\n @return whether parsing should proceed\n @note binary formats may report the number of elements\n */\n virtual bool start_object(std::size_t elements) = 0;\n\n /*!\n @brief an object key was read\n @param[in] val object key\n @return whether parsing should proceed\n @note It is safe to move the passed string.\n */\n virtual bool key(string_t& val) = 0;\n\n /*!\n @brief the end of an object was read\n @return whether parsing should proceed\n */\n virtual bool end_object() = 0;\n\n /*!\n @brief the beginning of an array was read\n @param[in] elements number of array elements or -1 if unknown\n @return whether parsing should proceed\n @note binary formats may report the number of elements\n */\n virtual bool start_array(std::size_t elements) = 0;\n\n /*!\n @brief the end of an array was read\n @return whether parsing should proceed\n */\n virtual bool end_array() = 0;\n\n /*!\n @brief a parse error occurred\n @param[in] position the position in the input where the error occurs\n @param[in] last_token the last read token\n @param[in] ex an exception object describing the error\n @return whether parsing should proceed (must return false)\n */\n virtual bool parse_error(std::size_t position,\n const std::string& last_token,\n const detail::exception& ex) = 0;\n\n json_sax() = default;\n json_sax(const json_sax&) = default;\n json_sax(json_sax&&) noexcept = default;\n json_sax& operator=(const json_sax&) = default;\n json_sax& operator=(json_sax&&) noexcept = default;\n virtual ~json_sax() = default;\n};\n\nnamespace detail\n{\nconstexpr std::size_t unknown_size()\n{\n return (std::numeric_limits::max)();\n}\n\n/*!\n@brief SAX implementation to create a JSON value from SAX events\n\nThis class implements the @ref json_sax interface and processes the SAX events\nto create a JSON value which makes it basically a DOM parser. The structure or\nhierarchy of the JSON value is managed by the stack `ref_stack` which contains\na pointer to the respective array or object for each recursion depth.\n\nAfter successful parsing, the value that is passed by reference to the\nconstructor contains the parsed value.\n\n@tparam BasicJsonType the JSON type\n*/\ntemplate\nclass json_sax_dom_parser\n{\n public:\n using number_integer_t = typename BasicJsonType::number_integer_t;\n using number_unsigned_t = typename BasicJsonType::number_unsigned_t;\n using number_float_t = typename BasicJsonType::number_float_t;\n using string_t = typename BasicJsonType::string_t;\n using binary_t = typename BasicJsonType::binary_t;\n using lexer_t = lexer;\n\n /*!\n @param[in,out] r reference to a JSON value that is manipulated while\n parsing\n @param[in] allow_exceptions_ whether parse errors yield exceptions\n */\n explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true, lexer_t* lexer_ = nullptr)\n : root(r), allow_exceptions(allow_exceptions_), m_lexer_ref(lexer_)\n {}\n\n // make class move-only\n json_sax_dom_parser(const json_sax_dom_parser&) = delete;\n json_sax_dom_parser(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)\n json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete;\n json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)\n ~json_sax_dom_parser() = default;\n\n bool null()\n {\n handle_value(nullptr);\n return true;\n }\n\n bool boolean(bool val)\n {\n handle_value(val);\n return true;\n }\n\n bool number_integer(number_integer_t val)\n {\n handle_value(val);\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val)\n {\n handle_value(val);\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& /*unused*/)\n {\n handle_value(val);\n return true;\n }\n\n bool string(string_t& val)\n {\n handle_value(val);\n return true;\n }\n\n bool binary(binary_t& val)\n {\n handle_value(std::move(val));\n return true;\n }\n\n bool start_object(std::size_t len)\n {\n ref_stack.push_back(handle_value(BasicJsonType::value_t::object));\n\n#if JSON_DIAGNOSTIC_POSITIONS\n // Manually set the start position of the object here.\n // Ensure this is after the call to handle_value to ensure correct start position.\n if (m_lexer_ref)\n {\n // Lexer has read the first character of the object, so\n // subtract 1 from the position to get the correct start position.\n ref_stack.back()->start_position = m_lexer_ref->get_position() - 1;\n }\n#endif\n\n if (JSON_HEDLEY_UNLIKELY(len != detail::unknown_size() && len > ref_stack.back()->max_size()))\n {\n JSON_THROW(out_of_range::create(408, concat(\"excessive object size: \", std::to_string(len)), ref_stack.back()));\n }\n\n return true;\n }\n\n bool key(string_t& val)\n {\n JSON_ASSERT(!ref_stack.empty());\n JSON_ASSERT(ref_stack.back()->is_object());\n\n // add null at the given key and store the reference for later\n object_element = &(ref_stack.back()->m_data.m_value.object->operator[](val));\n return true;\n }\n\n bool end_object()\n {\n JSON_ASSERT(!ref_stack.empty());\n JSON_ASSERT(ref_stack.back()->is_object());\n\n#if JSON_DIAGNOSTIC_POSITIONS\n if (m_lexer_ref)\n {\n // Lexer's position is past the closing brace, so set that as the end position.\n ref_stack.back()->end_position = m_lexer_ref->get_position();\n }\n#endif\n\n ref_stack.back()->set_parents();\n ref_stack.pop_back();\n return true;\n }\n\n bool start_array(std::size_t len)\n {\n ref_stack.push_back(handle_value(BasicJsonType::value_t::array));\n\n#if JSON_DIAGNOSTIC_POSITIONS\n // Manually set the start position of the array here.\n // Ensure this is after the call to handle_value to ensure correct start position.\n if (m_lexer_ref)\n {\n ref_stack.back()->start_position = m_lexer_ref->get_position() - 1;\n }\n#endif\n\n if (JSON_HEDLEY_UNLIKELY(len != detail::unknown_size() && len > ref_stack.back()->max_size()))\n {\n JSON_THROW(out_of_range::create(408, concat(\"excessive array size: \", std::to_string(len)), ref_stack.back()));\n }\n\n return true;\n }\n\n bool end_array()\n {\n JSON_ASSERT(!ref_stack.empty());\n JSON_ASSERT(ref_stack.back()->is_array());\n\n#if JSON_DIAGNOSTIC_POSITIONS\n if (m_lexer_ref)\n {\n // Lexer's position is past the closing bracket, so set that as the end position.\n ref_stack.back()->end_position = m_lexer_ref->get_position();\n }\n#endif\n\n ref_stack.back()->set_parents();\n ref_stack.pop_back();\n return true;\n }\n\n template\n bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,\n const Exception& ex)\n {\n errored = true;\n static_cast(ex);\n if (allow_exceptions)\n {\n JSON_THROW(ex);\n }\n return false;\n }\n\n constexpr bool is_errored() const\n {\n return errored;\n }\n\n private:\n\n#if JSON_DIAGNOSTIC_POSITIONS\n void handle_diagnostic_positions_for_json_value(BasicJsonType& v)\n {\n if (m_lexer_ref)\n {\n // Lexer has read past the current field value, so set the end position to the current position.\n // The start position will be set below based on the length of the string representation\n // of the value.\n v.end_position = m_lexer_ref->get_position();\n\n switch (v.type())\n {\n case value_t::boolean:\n {\n // 4 and 5 are the string length of \"true\" and \"false\"\n v.start_position = v.end_position - (v.m_data.m_value.boolean ? 4 : 5);\n break;\n }\n\n case value_t::null:\n {\n // 4 is the string length of \"null\"\n v.start_position = v.end_position - 4;\n break;\n }\n\n case value_t::string:\n {\n // escape sequences make the token longer than the value it\n // parses to, so the start position cannot be derived from\n // the value; use the offset the lexer recorded instead\n v.start_position = m_lexer_ref->get_token_start_position();\n break;\n }\n\n // As we handle the start and end positions for values created during parsing,\n // we do not expect the following value type to be called. Regardless, set the positions\n // in case this is created manually or through a different constructor. Exclude from lcov\n // since the exact condition of this switch is esoteric.\n // LCOV_EXCL_START\n case value_t::discarded:\n {\n v.end_position = std::string::npos;\n v.start_position = v.end_position;\n break;\n }\n // LCOV_EXCL_STOP\n case value_t::binary:\n case value_t::number_integer:\n case value_t::number_unsigned:\n case value_t::number_float:\n {\n v.start_position = v.end_position - m_lexer_ref->get_string().size();\n break;\n }\n case value_t::object:\n case value_t::array:\n {\n // object and array are handled in start_object() and start_array() handlers\n // skip setting the values here.\n break;\n }\n default: // LCOV_EXCL_LINE\n // Handle all possible types discretely, default handler should never be reached.\n JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert,-warnings-as-errors) LCOV_EXCL_LINE\n }\n }\n }\n#endif\n\n /*!\n @invariant If the ref stack is empty, then the passed value will be the new\n root.\n @invariant If the ref stack contains a value, then it is an array or an\n object to which we can add elements\n */\n template\n JSON_HEDLEY_RETURNS_NON_NULL\n BasicJsonType* handle_value(Value&& v)\n {\n if (ref_stack.empty())\n {\n root = BasicJsonType(std::forward(v));\n\n#if JSON_DIAGNOSTIC_POSITIONS\n handle_diagnostic_positions_for_json_value(root);\n#endif\n\n return &root;\n }\n\n JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object());\n\n if (ref_stack.back()->is_array())\n {\n ref_stack.back()->m_data.m_value.array->emplace_back(std::forward(v));\n\n#if JSON_DIAGNOSTIC_POSITIONS\n handle_diagnostic_positions_for_json_value(ref_stack.back()->m_data.m_value.array->back());\n#endif\n\n return &(ref_stack.back()->m_data.m_value.array->back());\n }\n\n JSON_ASSERT(ref_stack.back()->is_object());\n JSON_ASSERT(object_element);\n *object_element = BasicJsonType(std::forward(v));\n\n#if JSON_DIAGNOSTIC_POSITIONS\n handle_diagnostic_positions_for_json_value(*object_element);\n#endif\n\n return object_element;\n }\n\n /// the parsed JSON value\n BasicJsonType& root;\n /// stack to model hierarchy of values\n std::vector ref_stack {};\n /// helper to hold the reference for the next object element\n BasicJsonType* object_element = nullptr;\n /// whether a syntax error occurred\n bool errored = false;\n /// whether to throw exceptions in case of errors\n const bool allow_exceptions = true;\n /// the lexer reference to obtain the current position\n lexer_t* m_lexer_ref = nullptr;\n};\n\ntemplate\nclass json_sax_dom_callback_parser\n{\n public:\n using number_integer_t = typename BasicJsonType::number_integer_t;\n using number_unsigned_t = typename BasicJsonType::number_unsigned_t;\n using number_float_t = typename BasicJsonType::number_float_t;\n using string_t = typename BasicJsonType::string_t;\n using binary_t = typename BasicJsonType::binary_t;\n using parser_callback_t = typename BasicJsonType::parser_callback_t;\n using parse_event_t = typename BasicJsonType::parse_event_t;\n using lexer_t = lexer;\n\n json_sax_dom_callback_parser(BasicJsonType& r,\n parser_callback_t cb,\n const bool allow_exceptions_ = true,\n lexer_t* lexer_ = nullptr)\n : root(r), callback(std::move(cb)), allow_exceptions(allow_exceptions_), m_lexer_ref(lexer_)\n {\n keep_stack.push_back(true);\n }\n\n // make class move-only\n json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete;\n json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)\n json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete;\n json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)\n ~json_sax_dom_callback_parser() = default;\n\n bool null()\n {\n handle_value(nullptr);\n return true;\n }\n\n bool boolean(bool val)\n {\n handle_value(val);\n return true;\n }\n\n bool number_integer(number_integer_t val)\n {\n handle_value(val);\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val)\n {\n handle_value(val);\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& /*unused*/)\n {\n handle_value(val);\n return true;\n }\n\n bool string(string_t& val)\n {\n handle_value(val);\n return true;\n }\n\n bool binary(binary_t& val)\n {\n handle_value(std::move(val));\n return true;\n }\n\n bool start_object(std::size_t len)\n {\n // check callback for object start\n const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::object_start, discarded);\n keep_stack.push_back(keep);\n\n auto val = handle_value(BasicJsonType::value_t::object, true);\n ref_stack.push_back(val.second);\n\n if (ref_stack.back())\n {\n\n#if JSON_DIAGNOSTIC_POSITIONS\n // Manually set the start position of the object here.\n // Ensure this is after the call to handle_value to ensure correct start position.\n if (m_lexer_ref)\n {\n // Lexer has read the first character of the object, so\n // subtract 1 from the position to get the correct start position.\n ref_stack.back()->start_position = m_lexer_ref->get_position() - 1;\n }\n#endif\n\n // check object limit\n if (JSON_HEDLEY_UNLIKELY(len != detail::unknown_size() && len > ref_stack.back()->max_size()))\n {\n JSON_THROW(out_of_range::create(408, concat(\"excessive object size: \", std::to_string(len)), ref_stack.back()));\n }\n }\n return true;\n }\n\n bool key(string_t& val)\n {\n BasicJsonType k = BasicJsonType(val);\n\n // check callback for the key\n const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::key, k);\n key_keep_stack.push_back(keep);\n\n // add discarded value at the given key and store the reference for later\n if (keep && ref_stack.back())\n {\n object_element = &(ref_stack.back()->m_data.m_value.object->operator[](val) = discarded);\n }\n\n return true;\n }\n\n bool end_object()\n {\n if (ref_stack.back())\n {\n if (!callback(static_cast(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))\n {\n // discard object\n *ref_stack.back() = discarded;\n\n#if JSON_DIAGNOSTIC_POSITIONS\n // Set start/end positions for discarded object.\n handle_diagnostic_positions_for_json_value(*ref_stack.back());\n#endif\n }\n else\n {\n\n#if JSON_DIAGNOSTIC_POSITIONS\n if (m_lexer_ref)\n {\n // Lexer's position is past the closing brace, so set that as the end position.\n ref_stack.back()->end_position = m_lexer_ref->get_position();\n }\n#endif\n\n ref_stack.back()->set_parents();\n }\n }\n\n JSON_ASSERT(!ref_stack.empty());\n JSON_ASSERT(!keep_stack.empty());\n ref_stack.pop_back();\n keep_stack.pop_back();\n\n if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_structured())\n {\n // remove discarded value\n remove_discarded_value(*ref_stack.back());\n }\n\n return true;\n }\n\n bool start_array(std::size_t len)\n {\n const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::array_start, discarded);\n keep_stack.push_back(keep);\n\n auto val = handle_value(BasicJsonType::value_t::array, true);\n ref_stack.push_back(val.second);\n\n if (ref_stack.back())\n {\n\n#if JSON_DIAGNOSTIC_POSITIONS\n // Manually set the start position of the array here.\n // Ensure this is after the call to handle_value to ensure correct start position.\n if (m_lexer_ref)\n {\n // Lexer has read the first character of the array, so\n // subtract 1 from the position to get the correct start position.\n ref_stack.back()->start_position = m_lexer_ref->get_position() - 1;\n }\n#endif\n\n // check array limit\n if (JSON_HEDLEY_UNLIKELY(len != detail::unknown_size() && len > ref_stack.back()->max_size()))\n {\n JSON_THROW(out_of_range::create(408, concat(\"excessive array size: \", std::to_string(len)), ref_stack.back()));\n }\n }\n\n return true;\n }\n\n bool end_array()\n {\n bool keep = true;\n const bool stored = ref_stack.back() != nullptr;\n\n if (stored)\n {\n keep = callback(static_cast(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());\n if (keep)\n {\n\n#if JSON_DIAGNOSTIC_POSITIONS\n if (m_lexer_ref)\n {\n // Lexer's position is past the closing bracket, so set that as the end position.\n ref_stack.back()->end_position = m_lexer_ref->get_position();\n }\n#endif\n\n ref_stack.back()->set_parents();\n }\n else\n {\n // discard array\n *ref_stack.back() = discarded;\n\n#if JSON_DIAGNOSTIC_POSITIONS\n // Set start/end positions for discarded array.\n handle_diagnostic_positions_for_json_value(*ref_stack.back());\n#endif\n }\n }\n\n JSON_ASSERT(!ref_stack.empty());\n JSON_ASSERT(!keep_stack.empty());\n ref_stack.pop_back();\n keep_stack.pop_back();\n\n // remove discarded value\n if (!ref_stack.empty() && ref_stack.back())\n {\n if (!keep && ref_stack.back()->is_array())\n {\n ref_stack.back()->m_data.m_value.array->pop_back();\n }\n else if ((!keep || !stored) && ref_stack.back()->is_object())\n {\n // the array is either still stored under its key or was never\n // stored, leaving the placeholder key() wrote; both show up as\n // a discarded member of the parent object\n remove_discarded_value(*ref_stack.back());\n }\n }\n\n return true;\n }\n\n template\n bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,\n const Exception& ex)\n {\n errored = true;\n static_cast(ex);\n if (allow_exceptions)\n {\n JSON_THROW(ex);\n }\n return false;\n }\n\n constexpr bool is_errored() const\n {\n return errored;\n }\n\n private:\n\n#if JSON_DIAGNOSTIC_POSITIONS\n void handle_diagnostic_positions_for_json_value(BasicJsonType& v)\n {\n if (m_lexer_ref)\n {\n // Lexer has read past the current field value, so set the end position to the current position.\n // The start position will be set below based on the length of the string representation\n // of the value.\n v.end_position = m_lexer_ref->get_position();\n\n switch (v.type())\n {\n case value_t::boolean:\n {\n // 4 and 5 are the string length of \"true\" and \"false\"\n v.start_position = v.end_position - (v.m_data.m_value.boolean ? 4 : 5);\n break;\n }\n\n case value_t::null:\n {\n // 4 is the string length of \"null\"\n v.start_position = v.end_position - 4;\n break;\n }\n\n case value_t::string:\n {\n // escape sequences make the token longer than the value it\n // parses to, so the start position cannot be derived from\n // the value; use the offset the lexer recorded instead\n v.start_position = m_lexer_ref->get_token_start_position();\n break;\n }\n\n case value_t::discarded:\n {\n v.end_position = std::string::npos;\n v.start_position = v.end_position;\n break;\n }\n\n case value_t::binary:\n case value_t::number_integer:\n case value_t::number_unsigned:\n case value_t::number_float:\n {\n v.start_position = v.end_position - m_lexer_ref->get_string().size();\n break;\n }\n\n case value_t::object:\n case value_t::array:\n {\n // object and array are handled in start_object() and start_array() handlers\n // skip setting the values here.\n break;\n }\n default: // LCOV_EXCL_LINE\n // Handle all possible types discretely, default handler should never be reached.\n JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert,-warnings-as-errors) LCOV_EXCL_LINE\n }\n }\n }\n#endif\n\n /// remove the discarded value the callback rejected from its parent\n static void remove_discarded_value(BasicJsonType& parent)\n {\n for (auto it = parent.begin(); it != parent.end(); ++it)\n {\n if (it->is_discarded())\n {\n parent.erase(it);\n break;\n }\n }\n }\n\n /*!\n @param[in] v value to add to the JSON value we build during parsing\n @param[in] skip_callback whether we should skip calling the callback\n function; this is required after start_array() and\n start_object() SAX events, because otherwise we would call the\n callback function with an empty array or object, respectively.\n\n @invariant If the ref stack is empty, then the passed value will be the new\n root.\n @invariant If the ref stack contains a value, then it is an array or an\n object to which we can add elements\n\n @return pair of boolean (whether value should be kept) and pointer (to the\n passed value in the ref_stack hierarchy; nullptr if not kept)\n */\n template\n std::pair handle_value(Value&& v, const bool skip_callback = false)\n {\n JSON_ASSERT(!keep_stack.empty());\n\n // do not handle this value if we know it would be added to a discarded\n // container\n if (!keep_stack.back())\n {\n return {false, nullptr};\n }\n\n // create value\n auto value = BasicJsonType(std::forward(v));\n\n#if JSON_DIAGNOSTIC_POSITIONS\n handle_diagnostic_positions_for_json_value(value);\n#endif\n\n // check callback\n const bool keep = skip_callback || callback(static_cast(ref_stack.size()), parse_event_t::value, value);\n\n // do not handle this value if we just learnt it shall be discarded\n if (!keep)\n {\n // if the value was to become an object member, key() already\n // stored a placeholder for it that has to be removed again\n if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_object())\n {\n JSON_ASSERT(!key_keep_stack.empty());\n const bool placeholder_stored = key_keep_stack.back();\n key_keep_stack.pop_back();\n if (placeholder_stored)\n {\n remove_discarded_value(*ref_stack.back());\n }\n }\n return {false, nullptr};\n }\n\n if (ref_stack.empty())\n {\n root = std::move(value);\n return {true, & root};\n }\n\n // skip this value if we already decided to skip the parent\n // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)\n if (!ref_stack.back())\n {\n return {false, nullptr};\n }\n\n // we now only expect arrays and objects\n JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object());\n\n // array\n if (ref_stack.back()->is_array())\n {\n ref_stack.back()->m_data.m_value.array->emplace_back(std::move(value));\n return {true, & (ref_stack.back()->m_data.m_value.array->back())};\n }\n\n // object\n JSON_ASSERT(ref_stack.back()->is_object());\n // check if we should store an element for the current key\n JSON_ASSERT(!key_keep_stack.empty());\n const bool store_element = key_keep_stack.back();\n key_keep_stack.pop_back();\n\n if (!store_element)\n {\n return {false, nullptr};\n }\n\n JSON_ASSERT(object_element);\n *object_element = std::move(value);\n return {true, object_element};\n }\n\n /// the parsed JSON value\n BasicJsonType& root;\n /// stack to model hierarchy of values\n std::vector ref_stack {};\n /// stack to manage which values to keep\n std::vector keep_stack {}; // NOLINT(readability-redundant-member-init)\n /// stack to manage which object keys to keep\n std::vector key_keep_stack {}; // NOLINT(readability-redundant-member-init)\n /// helper to hold the reference for the next object element\n BasicJsonType* object_element = nullptr;\n /// whether a syntax error occurred\n bool errored = false;\n /// callback function\n const parser_callback_t callback = nullptr;\n /// whether to throw exceptions in case of errors\n const bool allow_exceptions = true;\n /// a discarded value for the callback\n BasicJsonType discarded = BasicJsonType::value_t::discarded;\n /// the lexer reference to obtain the current position\n lexer_t* m_lexer_ref = nullptr;\n};\n\ntemplate\nclass json_sax_acceptor\n{\n public:\n using number_integer_t = typename BasicJsonType::number_integer_t;\n using number_unsigned_t = typename BasicJsonType::number_unsigned_t;\n using number_float_t = typename BasicJsonType::number_float_t;\n using string_t = typename BasicJsonType::string_t;\n using binary_t = typename BasicJsonType::binary_t;\n\n bool null()\n {\n return true;\n }\n\n bool boolean(bool /*unused*/)\n {\n return true;\n }\n\n bool number_integer(number_integer_t /*unused*/)\n {\n return true;\n }\n\n bool number_unsigned(number_unsigned_t /*unused*/)\n {\n return true;\n }\n\n bool number_float(number_float_t /*unused*/, const string_t& /*unused*/)\n {\n return true;\n }\n\n bool string(string_t& /*unused*/)\n {\n return true;\n }\n\n bool binary(binary_t& /*unused*/)\n {\n return true;\n }\n\n bool start_object(std::size_t /*unused*/ = detail::unknown_size())\n {\n return true;\n }\n\n bool key(string_t& /*unused*/)\n {\n return true;\n }\n\n bool end_object()\n {\n return true;\n }\n\n bool start_array(std::size_t /*unused*/ = detail::unknown_size())\n {\n return true;\n }\n\n bool end_array()\n {\n return true;\n }\n\n bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/)\n {\n return false;\n }\n};\n\n} // namespace detail\nNLOHMANN_JSON_NAMESPACE_END", "messages": null, "tools": null} {"id": "6db23a6a4ac77827", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/from_msgpack.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 555, "sha256": "84f91ea402fdd94b24cf5674b6188fb0089702c86c249f3ee4138c2013c02c33", "text": "#include \n#include \n#include \n\nusing json = nlohmann::json;\n\nint main()\n{\n // create byte vector\n std::vector v = {0x82, 0xa7, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x63,\n 0x74, 0xc3, 0xa6, 0x73, 0x63, 0x68, 0x65, 0x6d,\n 0x61, 0x00\n };\n\n // deserialize it with MessagePack\n json j = json::from_msgpack(v);\n\n // print the deserialized JSON value\n std::cout << std::setw(2) << j << std::endl;\n}", "messages": null, "tools": null} {"id": "6e02bc53e580d099", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/src/unit-pointer_access.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 21156, "sha256": "a59de7827dffb6283fd72b09c52a6c019687a3f999aafaeab56611e75aeb47ef", "text": "// __ _____ _____ _____\n// __| | __| | | | JSON for Modern C++ (supporting code)\n// | | |__ | | | | | | version 3.12.0\n// |_____|_____|_____|_|___| https://github.com/nlohmann/json\n//\n// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann \n// SPDX-License-Identifier: MIT\n\n#include \"doctest_compatibility.h\"\n\n#include \nusing nlohmann::json;\n\nTEST_CASE(\"pointer access\")\n{\n SECTION(\"pointer access to object_t\")\n {\n using test_type = json::object_t;\n json value = {{\"one\", 1}, {\"two\", 2}};\n\n // check if pointers are returned correctly\n const test_type* p1 = value.get_ptr();\n CHECK(p1 == value.get_ptr());\n CHECK(*p1 == value.get());\n\n const test_type* p2 = value.get_ptr();\n CHECK(p2 == value.get_ptr());\n CHECK(*p2 == value.get());\n\n const test_type* const p3 = value.get_ptr();\n CHECK(p3 == value.get_ptr());\n CHECK(*p3 == value.get());\n\n // check if null pointers are returned correctly\n CHECK(value.get_ptr() != nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n }\n\n SECTION(\"pointer access to const object_t\")\n {\n using test_type = const json::object_t;\n const json value = {{\"one\", 1}, {\"two\", 2}};\n\n // check if pointers are returned correctly\n test_type* p1 = value.get_ptr();\n CHECK(p1 == value.get_ptr());\n CHECK(*p1 == value.get());\n\n const test_type* p2 = value.get_ptr();\n CHECK(p2 == value.get_ptr());\n CHECK(*p2 == value.get());\n\n const test_type* const p3 = value.get_ptr();\n CHECK(p3 == value.get_ptr());\n CHECK(*p3 == value.get());\n\n // check if null pointers are returned correctly\n CHECK(value.get_ptr() != nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n }\n\n SECTION(\"pointer access to array_t\")\n {\n using test_type = json::array_t;\n json value = {1, 2, 3, 4};\n\n // check if pointers are returned correctly\n const test_type* p1 = value.get_ptr();\n CHECK(p1 == value.get_ptr());\n CHECK(*p1 == value.get());\n\n const test_type* p2 = value.get_ptr();\n CHECK(p2 == value.get_ptr());\n CHECK(*p2 == value.get());\n\n const test_type* const p3 = value.get_ptr();\n CHECK(p3 == value.get_ptr());\n CHECK(*p3 == value.get());\n\n // check if null pointers are returned correctly\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() != nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n }\n\n SECTION(\"pointer access to const array_t\")\n {\n using test_type = const json::array_t;\n const json value = {1, 2, 3, 4};\n\n // check if pointers are returned correctly\n test_type* p1 = value.get_ptr();\n CHECK(p1 == value.get_ptr());\n CHECK(*p1 == value.get());\n\n const test_type* p2 = value.get_ptr();\n CHECK(p2 == value.get_ptr());\n CHECK(*p2 == value.get());\n\n const test_type* const p3 = value.get_ptr();\n CHECK(p3 == value.get_ptr());\n CHECK(*p3 == value.get());\n\n // check if null pointers are returned correctly\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() != nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n }\n\n SECTION(\"pointer access to string_t\")\n {\n using test_type = json::string_t;\n json value = \"hello\";\n\n // check if pointers are returned correctly\n const test_type* p1 = value.get_ptr();\n CHECK(p1 == value.get_ptr());\n CHECK(*p1 == value.get());\n\n const test_type* p2 = value.get_ptr();\n CHECK(p2 == value.get_ptr());\n CHECK(*p2 == value.get());\n\n const test_type* const p3 = value.get_ptr();\n CHECK(p3 == value.get_ptr());\n CHECK(*p3 == value.get());\n\n // check if null pointers are returned correctly\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() != nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n }\n\n SECTION(\"pointer access to const string_t\")\n {\n using test_type = const json::string_t;\n const json value = \"hello\";\n\n // check if pointers are returned correctly\n test_type* p1 = value.get_ptr();\n CHECK(p1 == value.get_ptr());\n CHECK(*p1 == value.get());\n\n const test_type* p2 = value.get_ptr();\n CHECK(p2 == value.get_ptr());\n CHECK(*p2 == value.get());\n\n const test_type* const p3 = value.get_ptr();\n CHECK(p3 == value.get_ptr());\n CHECK(*p3 == value.get());\n\n // check if null pointers are returned correctly\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() != nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n }\n\n SECTION(\"pointer access to boolean_t\")\n {\n using test_type = json::boolean_t;\n json value = false;\n\n // check if pointers are returned correctly\n const test_type* p1 = value.get_ptr();\n CHECK(p1 == value.get_ptr());\n CHECK(*p1 == value.get());\n\n const test_type* p2 = value.get_ptr();\n CHECK(p2 == value.get_ptr());\n CHECK(*p2 == value.get());\n\n const test_type* const p3 = value.get_ptr();\n CHECK(p3 == value.get_ptr());\n CHECK(*p3 == value.get());\n\n // check if null pointers are returned correctly\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() != nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n }\n\n SECTION(\"pointer access to const boolean_t\")\n {\n using test_type = const json::boolean_t;\n const json value = false;\n\n // check if pointers are returned correctly\n test_type* p1 = value.get_ptr();\n CHECK(p1 == value.get_ptr());\n //CHECK(*p1 == value.get());\n\n const test_type* p2 = value.get_ptr();\n CHECK(p2 == value.get_ptr());\n CHECK(*p2 == value.get());\n\n const test_type* const p3 = value.get_ptr();\n CHECK(p3 == value.get_ptr());\n CHECK(*p3 == value.get());\n\n // check if null pointers are returned correctly\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() != nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n }\n\n SECTION(\"pointer access to number_integer_t\")\n {\n using test_type = json::number_integer_t;\n json value = 23;\n\n // check if pointers are returned correctly\n const test_type* p1 = value.get_ptr();\n CHECK(p1 == value.get_ptr());\n CHECK(*p1 == value.get());\n\n const test_type* p2 = value.get_ptr();\n CHECK(p2 == value.get_ptr());\n CHECK(*p2 == value.get());\n\n const test_type* const p3 = value.get_ptr();\n CHECK(p3 == value.get_ptr());\n CHECK(*p3 == value.get());\n\n // check if null pointers are returned correctly\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() != nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n }\n\n SECTION(\"pointer access to const number_integer_t\")\n {\n using test_type = const json::number_integer_t;\n const json value = 23;\n\n // check if pointers are returned correctly\n test_type* p1 = value.get_ptr();\n CHECK(p1 == value.get_ptr());\n CHECK(*p1 == value.get());\n\n const test_type* p2 = value.get_ptr();\n CHECK(p2 == value.get_ptr());\n CHECK(*p2 == value.get());\n\n const test_type* const p3 = value.get_ptr();\n CHECK(p3 == value.get_ptr());\n CHECK(*p3 == value.get());\n\n // check if null pointers are returned correctly\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() != nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n }\n\n SECTION(\"pointer access to number_unsigned_t\")\n {\n using test_type = json::number_unsigned_t;\n json value = 23u;\n\n // check if pointers are returned correctly\n const test_type* p1 = value.get_ptr();\n CHECK(p1 == value.get_ptr());\n CHECK(*p1 == value.get());\n\n const test_type* p2 = value.get_ptr();\n CHECK(p2 == value.get_ptr());\n CHECK(*p2 == value.get());\n\n const test_type* const p3 = value.get_ptr();\n CHECK(p3 == value.get_ptr());\n CHECK(*p3 == value.get());\n\n // check if null pointers are returned correctly\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() != nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n }\n\n SECTION(\"pointer access to const number_unsigned_t\")\n {\n using test_type = const json::number_unsigned_t;\n const json value = 23u;\n\n // check if pointers are returned correctly\n test_type* p1 = value.get_ptr();\n CHECK(p1 == value.get_ptr());\n CHECK(*p1 == value.get());\n\n const test_type* p2 = value.get_ptr();\n CHECK(p2 == value.get_ptr());\n CHECK(*p2 == value.get());\n\n const test_type* const p3 = value.get_ptr();\n CHECK(p3 == value.get_ptr());\n CHECK(*p3 == value.get());\n\n // check if null pointers are returned correctly\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() != nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n }\n\n SECTION(\"pointer access to number_float_t\")\n {\n using test_type = json::number_float_t;\n json value = 42.23;\n\n // check if pointers are returned correctly\n const test_type* p1 = value.get_ptr();\n CHECK(p1 == value.get_ptr());\n CHECK(*p1 == Approx(value.get()));\n\n const test_type* p2 = value.get_ptr();\n CHECK(p2 == value.get_ptr());\n CHECK(*p2 == Approx(value.get()));\n\n const test_type* const p3 = value.get_ptr();\n CHECK(p3 == value.get_ptr());\n CHECK(*p3 == Approx(value.get()));\n\n // check if null pointers are returned correctly\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() != nullptr);\n CHECK(value.get_ptr() == nullptr);\n }\n\n SECTION(\"pointer access to const number_float_t\")\n {\n using test_type = const json::number_float_t;\n const json value = 42.23;\n\n // check if pointers are returned correctly\n test_type* p1 = value.get_ptr();\n CHECK(p1 == value.get_ptr());\n CHECK(*p1 == Approx(value.get()));\n\n const test_type* p2 = value.get_ptr();\n CHECK(p2 == value.get_ptr());\n CHECK(*p2 == Approx(value.get()));\n\n const test_type* const p3 = value.get_ptr();\n CHECK(p3 == value.get_ptr());\n CHECK(*p3 == Approx(value.get()));\n\n // check if null pointers are returned correctly\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() != nullptr);\n CHECK(value.get_ptr() == nullptr);\n }\n\n SECTION(\"pointer access to const binary_t\")\n {\n using test_type = const json::binary_t;\n const json value = json::binary({1, 2, 3});\n\n // check if pointers are returned correctly\n test_type* p1 = value.get_ptr();\n CHECK(p1 == value.get_ptr());\n CHECK(*p1 == value.get());\n\n const test_type* p2 = value.get_ptr();\n CHECK(p2 == value.get_ptr());\n CHECK(*p2 == value.get());\n\n const test_type* const p3 = value.get_ptr();\n CHECK(p3 == value.get_ptr());\n CHECK(*p3 == value.get());\n\n // check if null pointers are returned correctly\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() != nullptr);\n }\n\n SECTION(\"pointer access to const binary_t\")\n {\n using test_type = const json::binary_t;\n const json value = json::binary({});\n\n // check if pointers are returned correctly\n test_type* p1 = value.get_ptr();\n CHECK(p1 == value.get_ptr());\n CHECK(*p1 == value.get());\n\n const test_type* p2 = value.get_ptr();\n CHECK(p2 == value.get_ptr());\n CHECK(*p2 == value.get());\n\n const test_type* const p3 = value.get_ptr();\n CHECK(p3 == value.get_ptr());\n CHECK(*p3 == value.get());\n\n // check if null pointers are returned correctly\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() == nullptr);\n CHECK(value.get_ptr() != nullptr);\n }\n}", "messages": null, "tools": null} {"id": "6e1401eb567fcee8", "category": "code", "domain": "code", "source": "flask", "license": "BSD-3-Clause", "license_url": "https://spdx.org/licenses/BSD-3-Clause.html", "path": "src/flask/templating.py", "lang": "python", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/pallets/flask", "commit": "6a2f545bfd8ed31e19066a299296917e034aca58", "collector": "tools/harvest.py"}, "chars": 7335, "sha256": "8c3b8dea4457ca2e8255917c4a03fc286ba5f8f23b30d3f0870f9a71bddb62c8", "text": "from __future__ import annotations\n\nimport typing as t\n\nfrom jinja2 import BaseLoader\nfrom jinja2 import Environment as BaseEnvironment\nfrom jinja2 import Template\nfrom jinja2 import TemplateNotFound\n\nfrom .ctx import AppContext\nfrom .globals import app_ctx\nfrom .helpers import stream_with_context\nfrom .signals import before_render_template\nfrom .signals import template_rendered\n\nif t.TYPE_CHECKING: # pragma: no cover\n from .sansio.app import App\n from .sansio.scaffold import Scaffold\n\n\ndef _default_template_ctx_processor() -> dict[str, t.Any]:\n \"\"\"Default template context processor. Replaces the ``request`` and ``g``\n proxies with their concrete objects for faster access.\n \"\"\"\n ctx = app_ctx._get_current_object()\n rv: dict[str, t.Any] = {\"g\": ctx.g}\n\n if ctx.has_request:\n rv[\"request\"] = ctx.request\n # The session proxy cannot be replaced, accessing it gets\n # RequestContext.session, which sets session.accessed.\n\n return rv\n\n\nclass Environment(BaseEnvironment):\n \"\"\"Works like a regular Jinja environment but has some additional\n knowledge of how Flask's blueprint works so that it can prepend the\n name of the blueprint to referenced templates if necessary.\n \"\"\"\n\n def __init__(self, app: App, **options: t.Any) -> None:\n if \"loader\" not in options:\n options[\"loader\"] = app.create_global_jinja_loader()\n BaseEnvironment.__init__(self, **options)\n self.app = app\n\n\nclass DispatchingJinjaLoader(BaseLoader):\n \"\"\"A loader that looks for templates in the application and all\n the blueprint folders.\n \"\"\"\n\n def __init__(self, app: App) -> None:\n self.app = app\n\n def get_source(\n self, environment: BaseEnvironment, template: str\n ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n if self.app.config[\"EXPLAIN_TEMPLATE_LOADING\"]:\n return self._get_source_explained(environment, template)\n return self._get_source_fast(environment, template)\n\n def _get_source_explained(\n self, environment: BaseEnvironment, template: str\n ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n attempts = []\n rv: tuple[str, str | None, t.Callable[[], bool] | None] | None\n trv: None | (tuple[str, str | None, t.Callable[[], bool] | None]) = None\n\n for srcobj, loader in self._iter_loaders(template):\n try:\n rv = loader.get_source(environment, template)\n if trv is None:\n trv = rv\n except TemplateNotFound:\n rv = None\n attempts.append((loader, srcobj, rv))\n\n from .debughelpers import explain_template_loading_attempts\n\n explain_template_loading_attempts(self.app, template, attempts)\n\n if trv is not None:\n return trv\n raise TemplateNotFound(template)\n\n def _get_source_fast(\n self, environment: BaseEnvironment, template: str\n ) -> tuple[str, str | None, t.Callable[[], bool] | None]:\n for _srcobj, loader in self._iter_loaders(template):\n try:\n return loader.get_source(environment, template)\n except TemplateNotFound:\n continue\n raise TemplateNotFound(template)\n\n def _iter_loaders(self, template: str) -> t.Iterator[tuple[Scaffold, BaseLoader]]:\n loader = self.app.jinja_loader\n if loader is not None:\n yield self.app, loader\n\n for blueprint in self.app.iter_blueprints():\n loader = blueprint.jinja_loader\n if loader is not None:\n yield blueprint, loader\n\n def list_templates(self) -> list[str]:\n result = set()\n loader = self.app.jinja_loader\n if loader is not None:\n result.update(loader.list_templates())\n\n for blueprint in self.app.iter_blueprints():\n loader = blueprint.jinja_loader\n if loader is not None:\n for template in loader.list_templates():\n result.add(template)\n\n return list(result)\n\n\ndef _render(ctx: AppContext, template: Template, context: dict[str, t.Any]) -> str:\n app = ctx.app\n app.update_template_context(ctx, context)\n before_render_template.send(\n app, _async_wrapper=app.ensure_sync, template=template, context=context\n )\n rv = template.render(context)\n template_rendered.send(\n app, _async_wrapper=app.ensure_sync, template=template, context=context\n )\n return rv\n\n\ndef render_template(\n template_name_or_list: str | Template | list[str | Template],\n **context: t.Any,\n) -> str:\n \"\"\"Render a template by name with the given context.\n\n :param template_name_or_list: The name of the template to render. If\n a list is given, the first name to exist will be rendered.\n :param context: The variables to make available in the template.\n \"\"\"\n ctx = app_ctx._get_current_object()\n template = ctx.app.jinja_env.get_or_select_template(template_name_or_list)\n return _render(ctx, template, context)\n\n\ndef render_template_string(source: str, **context: t.Any) -> str:\n \"\"\"Render a template from the given source string with the given\n context.\n\n :param source: The source code of the template to render.\n :param context: The variables to make available in the template.\n \"\"\"\n ctx = app_ctx._get_current_object()\n template = ctx.app.jinja_env.from_string(source)\n return _render(ctx, template, context)\n\n\ndef _stream(\n ctx: AppContext, template: Template, context: dict[str, t.Any]\n) -> t.Iterator[str]:\n app = ctx.app\n app.update_template_context(ctx, context)\n before_render_template.send(\n app, _async_wrapper=app.ensure_sync, template=template, context=context\n )\n\n def generate() -> t.Iterator[str]:\n yield from template.generate(context)\n template_rendered.send(\n app, _async_wrapper=app.ensure_sync, template=template, context=context\n )\n\n return stream_with_context(generate())\n\n\ndef stream_template(\n template_name_or_list: str | Template | list[str | Template],\n **context: t.Any,\n) -> t.Iterator[str]:\n \"\"\"Render a template by name with the given context as a stream.\n This returns an iterator of strings, which can be used as a\n streaming response from a view.\n\n :param template_name_or_list: The name of the template to render. If\n a list is given, the first name to exist will be rendered.\n :param context: The variables to make available in the template.\n\n .. versionadded:: 2.2\n \"\"\"\n ctx = app_ctx._get_current_object()\n template = ctx.app.jinja_env.get_or_select_template(template_name_or_list)\n return _stream(ctx, template, context)\n\n\ndef stream_template_string(source: str, **context: t.Any) -> t.Iterator[str]:\n \"\"\"Render a template from the given source string with the given\n context as a stream. This returns an iterator of strings, which can\n be used as a streaming response from a view.\n\n :param source: The source code of the template to render.\n :param context: The variables to make available in the template.\n\n .. versionadded:: 2.2\n \"\"\"\n ctx = app_ctx._get_current_object()\n template = ctx.app.jinja_env.from_string(source)\n return _stream(ctx, template, context)", "messages": null, "tools": null} {"id": "6e7493b68d92bd9b", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/features/parsing/parser_callbacks.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 7756, "sha256": "9f46bc250bb98a95f9118145c5515c52f4b438e3f03312adf6e1a72ab3b1a513", "text": "# Parser Callbacks\n\n## Overview\n\nWith a parser callback function, the result of parsing a JSON text can be influenced. When passed to `parse`, it is\ncalled on certain events (passed as `parse_event_t` via parameter `event`) with a set recursion depth `depth` and\ncontext JSON value `parsed`. The return value of the callback function is a boolean indicating whether the element that\nemitted the callback shall be kept or not.\n\nThe type of the callback function is:\n\n```cpp\ntemplate\nusing parser_callback_t =\n std::function;\n```\n\n\n## Callback event types\n\nWe distinguish six scenarios (determined by the event type) in which the callback function can be called. The following\ntable describes the values of the parameters `depth`, `event`, and `parsed`.\n\n| parameter `event` | description | parameter `depth` | parameter `parsed` |\n|-------------------------------|-----------------------------------------------------------|-------------------------------------------|----------------------------------|\n| `parse_event_t::object_start` | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded |\n| `parse_event_t::key` | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key |\n| `parse_event_t::object_end` | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object |\n| `parse_event_t::array_start` | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded |\n| `parse_event_t::array_end` | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array |\n| `parse_event_t::value` | the parser finished reading a JSON value | depth of the value | the parsed JSON value |\n\n??? example\n\n When parsing the following JSON text,\n \n ```json\n {\n \"name\": \"Berlin\",\n \"location\": [\n 52.519444,\n 13.406667\n ]\n }\n ```\n \n these calls are made to the callback function:\n \n | event | depth | parsed |\n | -------------- | ----- | ------ |\n | `object_start` | 0 | *discarded* |\n | `key` | 1 | `#!json \"name\"` |\n | `value` | 1 | `#!json \"Berlin\"` |\n | `key` | 1 | `#!json \"location\"` |\n | `array_start` | 1 | *discarded* |\n | `value` | 2 | `#!json 52.519444` |\n | `value` | 2 | `#!json 13.406667` |\n | `array_end` | 1 | `#!json [52.519444,13.406667]` |\n | `object_end` | 0 | `#!json {\"location\":[52.519444,13.406667],\"name\":\"Berlin\"}` |\n\n!!! note \"No built-in nesting depth limit\"\n\n The library has no built-in limit on recursion/nesting depth while parsing. A parser callback can only\n *discard* content it has already parsed (by returning `#!c false`); it cannot make parsing fail once a\n nesting limit is exceeded partway through reading a deeply nested value. If you need to reject over-deep\n untrusted input outright, track `depth` in a callback and `throw` from it once your limit is exceeded (a\n thrown exception propagates out of `parse()` as usual).\n\n## Return value\n\nDiscarding a value (i.e., returning `#!c false`) has different effects depending on the context in which the function\nwas called:\n\n- Discarded values in structured types are skipped. That is, the parser will behave as if the discarded value was never\n read.\n- In case a value outside a structured type is skipped, it is replaced with `#!json null`. This case happens if the\n top-level element is skipped.\n\n??? example\n\n The example below demonstrates the `parse()` function with and without callback function.\n\n ```cpp\n --8<-- \"examples/parse__string__parser_callback_t.cpp\"\n ```\n \n Output:\n\n ```json\n --8<-- \"examples/parse__string__parser_callback_t.output\"\n ```\n\n## Recipe: rejecting duplicate object keys\n\nThe JSON specification leaves the handling of objects with repeated keys up to the implementation. As described in\n[`object_t`](../../api/basic_json/object_t.md#behavior), it is unspecified which value for a repeated key ends up in\nthe resulting `#!c json` value -- once parsing has produced that value, the duplicate is already gone, because object\nstorage maps each key to a single value. If duplicate keys should instead be treated as an error, a parser callback\ncan detect them while the object is still being read, before that ambiguity ever applies.\n\n??? example\n\n ```cpp\n --8<-- \"examples/reject_duplicate_keys.cpp\"\n ```\n\n Output:\n\n ```json\n --8<-- \"examples/reject_duplicate_keys.output\"\n ```\n\nThis approach has two limitations:\n\n- The depth-indexed bookkeeping must account for the fact that `object_start` reports the depth of the *parent* of\n the object, while the `key` events inside that object are reported one depth deeper (see the event table above);\n it is easy to get this off by one for nested objects.\n- The thrown exception cannot carry a `parse_error`-style byte offset, because position tracking only exists inside\n the parser and lexer, not at the callback layer.\n\nFor strict validation with precise error positions, implementing a [SAX interface](sax_interface.md) instead gives\naccess to the parser's position information directly.\n\n## Recipe: streaming a large homogeneous array\n\nA common use case is a huge top-level array of many similarly-shaped objects, too large to hold entirely in\nmemory as a `#!c json` value. A parser callback can hand off each completed element to a user function and then\ndiscard it, so memory usage stays bounded by a single element (plus the not-yet-parsed tail of the input) rather\nthan the whole document. Since the top-level array's `array_start`/`array_end` are reported at `depth == 0` (its\nparent is the document root), the object elements it contains are reported at `depth == 1`:\n\n??? example\n\n ```cpp\n std::ifstream input(\"large_array.json\");\n\n auto callback = [](int depth, json::parse_event_t event, json& parsed) -> bool {\n if (depth == 1 && event == json::parse_event_t::object_end) {\n handle_element(parsed); // process the element, e.g. write it elsewhere\n return false; // discard it -- frees its memory before the next one is parsed\n }\n return true; // keep everything else, including the (by then empty) top-level array\n };\n\n json::parse(input, callback);\n ```\n\nIf the array's elements are scalars or nested arrays instead of objects, check for `parse_event_t::value` or\n`parse_event_t::array_end` at `depth == 1` instead. The same approach works for a top-level *object* of many\nhomogeneous values by checking `object_end`/`value` events at `depth == 1` there too.\n\n## Recipe: max nesting depth via a callback\n\nSince there is no built-in nesting-depth limit (see the note above), a callback can enforce one manually by\ntracking the maximum `depth` seen and throwing once it is exceeded:\n\n??? example\n\n ```cpp\n constexpr int max_depth = 32;\n\n auto callback = [](int depth, json::parse_event_t /*event*/, json& /*parsed*/) -> bool {\n if (depth > max_depth) {\n throw std::runtime_error(\"maximum nesting depth exceeded\");\n }\n return true;\n };\n\n json::parse(input, callback);\n ```", "messages": null, "tools": null} {"id": "6ec9299dd71bf708", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/dump.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 1471, "sha256": "ef81ce933c2030bebb010435600e00e550e45ff10923782d1ee4033240665470", "text": "#include \n#include \n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hellö 😀!\";\n\n // call dump()\n std::cout << \"objects:\" << '\\n'\n << j_object.dump() << \"\\n\\n\"\n << j_object.dump(-1) << \"\\n\\n\"\n << j_object.dump(0) << \"\\n\\n\"\n << j_object.dump(4) << \"\\n\\n\"\n << j_object.dump(1, '\\t') << \"\\n\\n\";\n\n std::cout << \"arrays:\" << '\\n'\n << j_array.dump() << \"\\n\\n\"\n << j_array.dump(-1) << \"\\n\\n\"\n << j_array.dump(0) << \"\\n\\n\"\n << j_array.dump(4) << \"\\n\\n\"\n << j_array.dump(1, '\\t') << \"\\n\\n\";\n\n std::cout << \"strings:\" << '\\n'\n << j_string.dump() << '\\n'\n << j_string.dump(-1, ' ', true) << '\\n';\n\n // create JSON value with invalid UTF-8 byte sequence\n json j_invalid = \"ä\\xA9ü\";\n try\n {\n std::cout << j_invalid.dump() << std::endl;\n }\n catch (const json::type_error& e)\n {\n std::cout << e.what() << std::endl;\n }\n\n std::cout << \"string with replaced invalid characters: \"\n << j_invalid.dump(-1, ' ', false, json::error_handler_t::replace)\n << \"\\nstring with ignored invalid characters: \"\n << j_invalid.dump(-1, ' ', false, json::error_handler_t::ignore)\n << '\\n';\n}", "messages": null, "tools": null} {"id": "6fb94a1010ede03a", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/src/unit-to_chars.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 34477, "sha256": "f14dc0539fa50d5460dfc88ba76bdd81214b19fcc130d7b52d36732dd4753949", "text": "// __ _____ _____ _____\n// __| | __| | | | JSON for Modern C++ (supporting code)\n// | | |__ | | | | | | version 3.12.0\n// |_____|_____|_____|_|___| https://github.com/nlohmann/json\n//\n// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann \n// SPDX-License-Identifier: MIT\n\n// XXX:\n// Only compile these tests if 'float' and 'double' are IEEE-754 single- and\n// double-precision numbers, resp.\n\n#include \"doctest_compatibility.h\"\n\n#include \nusing nlohmann::detail::dtoa_impl::reinterpret_bits;\n\nnamespace\n{\nfloat make_float(uint32_t sign_bit, uint32_t biased_exponent, uint32_t significand)\n{\n assert(sign_bit == 0 || sign_bit == 1);\n assert(biased_exponent <= 0xFF);\n assert(significand <= 0x007FFFFF);\n\n uint32_t bits = 0;\n\n bits |= sign_bit << 31;\n bits |= biased_exponent << 23;\n bits |= significand;\n\n return reinterpret_bits(bits);\n}\n\n// ldexp -- convert f * 2^e to IEEE single precision\nfloat make_float(uint64_t f, int e)\n{\n constexpr uint64_t kHiddenBit = 0x00800000;\n constexpr uint64_t kSignificandMask = 0x007FFFFF;\n constexpr int kPhysicalSignificandSize = 23; // Excludes the hidden bit.\n constexpr int kExponentBias = 0x7F + kPhysicalSignificandSize;\n constexpr int kDenormalExponent = 1 - kExponentBias;\n constexpr int kMaxExponent = 0xFF - kExponentBias;\n\n while (f > kHiddenBit + kSignificandMask)\n {\n f >>= 1;\n e++;\n }\n if (e >= kMaxExponent)\n {\n return std::numeric_limits::infinity();\n }\n if (e < kDenormalExponent)\n {\n return 0.0;\n }\n while (e > kDenormalExponent && (f & kHiddenBit) == 0)\n {\n f <<= 1;\n e--;\n }\n\n const uint64_t biased_exponent = (e == kDenormalExponent && (f & kHiddenBit) == 0)\n ? 0\n : static_cast(e + kExponentBias);\n\n const uint64_t bits = (f & kSignificandMask) | (biased_exponent << kPhysicalSignificandSize);\n return reinterpret_bits(static_cast(bits));\n}\n\ndouble make_double(uint64_t sign_bit, uint64_t biased_exponent, uint64_t significand)\n{\n assert(sign_bit == 0 || sign_bit == 1);\n assert(biased_exponent <= 0x7FF);\n assert(significand <= 0x000FFFFFFFFFFFFF);\n\n uint64_t bits = 0;\n\n bits |= sign_bit << 63;\n bits |= biased_exponent << 52;\n bits |= significand;\n\n return reinterpret_bits(bits);\n}\n\n// ldexp -- convert f * 2^e to IEEE double precision\ndouble make_double(uint64_t f, int e)\n{\n constexpr uint64_t kHiddenBit = 0x0010000000000000;\n constexpr uint64_t kSignificandMask = 0x000FFFFFFFFFFFFF;\n constexpr int kPhysicalSignificandSize = 52; // Excludes the hidden bit.\n constexpr int kExponentBias = 0x3FF + kPhysicalSignificandSize;\n constexpr int kDenormalExponent = 1 - kExponentBias;\n constexpr int kMaxExponent = 0x7FF - kExponentBias;\n\n while (f > kHiddenBit + kSignificandMask)\n {\n f >>= 1;\n e++;\n }\n if (e >= kMaxExponent)\n {\n return std::numeric_limits::infinity();\n }\n if (e < kDenormalExponent)\n {\n return 0.0;\n }\n while (e > kDenormalExponent && (f & kHiddenBit) == 0)\n {\n f <<= 1;\n e--;\n }\n\n const uint64_t biased_exponent = (e == kDenormalExponent && (f & kHiddenBit) == 0)\n ? 0\n : static_cast(e + kExponentBias);\n\n const uint64_t bits = (f & kSignificandMask) | (biased_exponent << kPhysicalSignificandSize);\n return reinterpret_bits(bits);\n}\n} // namespace\n\nTEST_CASE(\"digit gen\")\n{\n SECTION(\"single precision\")\n {\n auto check_float = [](float number, const std::string & digits, int expected_exponent)\n {\n CAPTURE(number)\n CAPTURE(digits)\n CAPTURE(expected_exponent)\n\n std::array buf{};\n int len = 0;\n int exponent = 0;\n nlohmann::detail::dtoa_impl::grisu2(buf.data(), len, exponent, number);\n\n CHECK(digits == std::string(buf.data(), buf.data() + len));\n CHECK(expected_exponent == exponent);\n };\n\n check_float(make_float(0, 0, 0x00000001), \"1\", -45); // min denormal\n check_float(make_float(0, 0, 0x007FFFFF), \"11754942\", -45); // max denormal\n check_float(make_float(0, 1, 0x00000000), \"11754944\", -45); // min normal\n check_float(make_float(0, 1, 0x00000001), \"11754945\", -45);\n check_float(make_float(0, 1, 0x007FFFFF), \"23509886\", -45);\n check_float(make_float(0, 2, 0x00000000), \"23509887\", -45);\n check_float(make_float(0, 2, 0x00000001), \"2350989\", -44);\n check_float(make_float(0, 24, 0x00000000), \"98607613\", -39); // fail if no special case in normalized boundaries\n check_float(make_float(0, 30, 0x00000000), \"63108872\", -37); // fail if no special case in normalized boundaries\n check_float(make_float(0, 31, 0x00000000), \"12621775\", -36); // fail if no special case in normalized boundaries\n check_float(make_float(0, 57, 0x00000000), \"84703295\", -29); // fail if no special case in normalized boundaries\n check_float(make_float(0, 254, 0x007FFFFE), \"34028233\", 31);\n check_float(make_float(0, 254, 0x007FFFFF), \"34028235\", 31); // max normal\n\n // V. Paxson and W. Kahan, \"A Program for Testing IEEE Binary-Decimal Conversion\", manuscript, May 1991,\n // ftp://ftp.ee.lbl.gov/testbase-report.ps.Z (report)\n // ftp://ftp.ee.lbl.gov/testbase.tar.Z (program)\n\n // Table 16: Stress Inputs for Converting 24-bit Binary to Decimal, < 1/2 ULP\n check_float(make_float(12676506, -102), \"25\", -25);\n check_float(make_float(12676506, -103), \"125\", -26);\n check_float(make_float(15445013, 86), \"1195\", 30);\n check_float(make_float(13734123, -138), \"39415\", -39);\n check_float(make_float(12428269, -130), \"913085\", -38);\n check_float(make_float(15334037, -146), \"1719005\", -43);\n check_float(make_float(11518287, -41), \"52379105\", -13);\n check_float(make_float(12584953, -145), \"2821644\", -43);\n check_float(make_float(15961084, -125), \"37524328\", -38);\n check_float(make_float(14915817, -146), \"16721209\", -44);\n check_float(make_float(10845484, -102), \"21388946\", -31);\n check_float(make_float(16431059, -61), \"7125836\", -18);\n\n // Table 17: Stress Inputs for Converting 24-bit Binary to Decimal, > 1/2 ULP\n check_float(make_float(16093626, 69), \"95\", 26);\n check_float(make_float( 9983778, 25), \"335\", 12);\n check_float(make_float(12745034, 104), \"2585\", 35);\n check_float(make_float(12706553, 72), \"60005\", 24);\n check_float(make_float(11005028, 45), \"387205\", 15);\n check_float(make_float(15059547, 71), \"3555835\", 22);\n check_float(make_float(16015691, -99), \"25268305\", -30);\n check_float(make_float( 8667859, 56), \"6245851\", 17);\n check_float(make_float(14855922, -82), \"30721327\", -25);\n check_float(make_float(14855922, -83), \"15360663\", -25);\n check_float(make_float(10144164, -110), \"781478\", -32);\n check_float(make_float(13248074, 95), \"52481028\", 28);\n }\n\n SECTION(\"double precision\")\n {\n auto check_double = [](double number, const std::string & digits, int expected_exponent)\n {\n CAPTURE(number)\n CAPTURE(digits)\n CAPTURE(expected_exponent)\n\n std::array buf{};\n int len = 0;\n int exponent = 0;\n nlohmann::detail::dtoa_impl::grisu2(buf.data(), len, exponent, number);\n\n CHECK(digits == std::string(buf.data(), buf.data() + len));\n CHECK(expected_exponent == exponent);\n };\n\n check_double(make_double(0, 0, 0x0000000000000001), \"5\", -324); // min denormal\n check_double(make_double(0, 0, 0x000FFFFFFFFFFFFF), \"2225073858507201\", -323); // max denormal\n check_double(make_double(0, 1, 0x0000000000000000), \"22250738585072014\", -324); // min normal\n check_double(make_double(0, 1, 0x0000000000000001), \"2225073858507202\", -323);\n check_double(make_double(0, 1, 0x000FFFFFFFFFFFFF), \"44501477170144023\", -324);\n check_double(make_double(0, 2, 0x0000000000000000), \"4450147717014403\", -323);\n check_double(make_double(0, 2, 0x0000000000000001), \"4450147717014404\", -323);\n check_double(make_double(0, 4, 0x0000000000000000), \"17800590868057611\", -323); // fail if no special case in normalized boundaries\n check_double(make_double(0, 5, 0x0000000000000000), \"35601181736115222\", -323); // fail if no special case in normalized boundaries\n check_double(make_double(0, 6, 0x0000000000000000), \"7120236347223045\", -322); // fail if no special case in normalized boundaries\n check_double(make_double(0, 10, 0x0000000000000000), \"11392378155556871\", -321); // fail if no special case in normalized boundaries\n check_double(make_double(0, 2046, 0x000FFFFFFFFFFFFE), \"17976931348623155\", 292);\n check_double(make_double(0, 2046, 0x000FFFFFFFFFFFFF), \"17976931348623157\", 292); // max normal\n\n // Test different paths in DigitGen\n check_double( 10000, \"1\", 4);\n check_double( 1200000, \"12\", 5);\n check_double(4.9406564584124654e-324, \"5\", -324); // exit integral loop\n check_double(2.2250738585072009e-308, \"2225073858507201\", -323); // exit fractional loop\n check_double( 1.82877982605164e-99, \"182877982605164\", -113);\n check_double( 1.1505466208671903e-09, \"11505466208671903\", -25);\n check_double( 5.5645893133766722e+20, \"5564589313376672\", 5);\n check_double( 53.034830388866226, \"53034830388866226\", -15);\n check_double( 0.0021066531670178605, \"21066531670178605\", -19);\n\n // V. Paxson and W. Kahan, \"A Program for Testing IEEE Binary-Decimal Conversion\", manuscript, May 1991,\n // ftp://ftp.ee.lbl.gov/testbase-report.ps.Z (report)\n // ftp://ftp.ee.lbl.gov/testbase.tar.Z (program)\n\n // Table 3: Stress Inputs for Converting 53-bit Binary to Decimal, < 1/2 ULP\n check_double(make_double(8511030020275656, -342) /* 9.5e-088 */, \"95\", -89);\n check_double(make_double(5201988407066741, -824) /* 4.65e-233 */, \"465\", -235);\n check_double(make_double(6406892948269899, +237) /* 1.415e+087 */, \"1415\", 84);\n check_double(make_double(8431154198732492, +72) /* 3.9815e+037 */, \"39815\", 33);\n check_double(make_double(6475049196144587, +99) /* 4.10405e+045 */, \"410405\", 40);\n check_double(make_double(8274307542972842, +726) /* 2.920845e+234 */, \"2920845\", 228);\n check_double(make_double(5381065484265332, -456) /* 2.8919465e-122 */, \"28919465\", -129);\n check_double(make_double(6761728585499734, -1057) /* 4.37877185e-303 */, \"437877185\", -311);\n check_double(make_double(7976538478610756, +376) /* 1.227701635e+129 */, \"1227701635\", 120);\n check_double(make_double(5982403858958067, +377) /* 1.8415524525e+129 */, \"18415524525\", 119);\n check_double(make_double(5536995190630837, +93) /* 5.48357443505e+043 */, \"548357443505\", 32);\n check_double(make_double(7225450889282194, +710) /* 3.891901811465e+229 */, \"3891901811465\", 217);\n check_double(make_double(7225450889282194, +709) /* 1.9459509057325e+229 */, \"19459509057325\", 216);\n check_double(make_double(8703372741147379, +117) /* 1.44609583816055e+051 */, \"144609583816055\", 37);\n check_double(make_double(8944262675275217, -1001) /* 4.173677474585315e-286 */, \"4173677474585315\", -301);\n check_double(make_double(7459803696087692, -707) /* 1.1079507728788885e-197 */, \"11079507728788885\", -213);\n check_double(make_double(6080469016670379, -381) /* 1.234550136632744e-099 */, \"1234550136632744\", -114);\n check_double(make_double(8385515147034757, +721) /* 9.2503171196036502e+232 */, \"925031711960365\", 218);\n check_double(make_double(7514216811389786, -828) /* 4.1980471502848898e-234 */, \"419804715028489\", -248);\n check_double(make_double(8397297803260511, -345) /* 1.1716315319786511e-088 */, \"11716315319786511\", -104);\n check_double(make_double(6733459239310543, +202) /* 4.3281007284461249e+076 */, \"4328100728446125\", 61);\n check_double(make_double(8091450587292794, -473) /* 3.3177101181600311e-127 */, \"3317710118160031\", -142);\n\n // Table 4: Stress Inputs for Converting 53-bit Binary to Decimal, > 1/2 ULP\n check_double(make_double(6567258882077402, +952) /* 2.5e+302 */, \"25\", 301);\n check_double(make_double(6712731423444934, +535) /* 7.55e+176 */, \"755\", 174);\n check_double(make_double(6712731423444934, +534) /* 3.775e+176 */, \"3775\", 173);\n check_double(make_double(5298405411573037, -957) /* 4.3495e-273 */, \"43495\", -277);\n check_double(make_double(5137311167659507, -144) /* 2.30365e-028 */, \"230365\", -33);\n check_double(make_double(6722280709661868, +363) /* 1.263005e+125 */, \"1263005\", 119);\n check_double(make_double(5344436398034927, -169) /* 7.1422105e-036 */, \"71422105\", -43);\n check_double(make_double(8369123604277281, -853) /* 1.39345735e-241 */, \"139345735\", -249);\n check_double(make_double(8995822108487663, -780) /* 1.414634485e-219 */, \"1414634485\", -228);\n check_double(make_double(8942832835564782, -383) /* 4.5392779195e-100 */, \"45392779195\", -110);\n check_double(make_double(8942832835564782, -384) /* 2.26963895975e-100 */, \"226963895975\", -111);\n check_double(make_double(8942832835564782, -385) /* 1.134819479875e-100 */, \"1134819479875\", -112);\n check_double(make_double(6965949469487146, -249) /* 7.7003665618895e-060 */, \"77003665618895\", -73);\n check_double(make_double(6965949469487146, -250) /* 3.85018328094475e-060 */, \"385018328094475\", -74);\n check_double(make_double(6965949469487146, -251) /* 1.925091640472375e-060 */, \"1925091640472375\", -75);\n check_double(make_double(7487252720986826, +548) /* 6.8985865317742005e+180 */, \"68985865317742005\", 164);\n check_double(make_double(5592117679628511, +164) /* 1.3076622631878654e+065 */, \"13076622631878654\", 49);\n check_double(make_double(8887055249355788, +665) /* 1.3605202075612124e+216 */, \"13605202075612124\", 200);\n check_double(make_double(6994187472632449, +690) /* 3.5928102174759597e+223 */, \"35928102174759597\", 207);\n check_double(make_double(8797576579012143, +588) /* 8.9125197712484552e+192 */, \"8912519771248455\", 177);\n check_double(make_double(7363326733505337, +272) /* 5.5876975736230114e+097 */, \"55876975736230114\", 81);\n check_double(make_double(8549497411294502, -448) /* 1.1762578307285404e-119 */, \"11762578307285404\", -135);\n\n // Table 20: Stress Inputs for Converting 56-bit Binary to Decimal, < 1/2 ULP\n check_double(make_double(50883641005312716, -172) /* 8.4999999999999993e-036 */, \"8499999999999999\", -51);\n check_double(make_double(38162730753984537, -170) /* 2.5499999999999999e-035 */, \"255\", -37);\n check_double(make_double(50832789069151999, -101) /* 2.0049999999999997e-014 */, \"20049999999999997\", -30);\n check_double(make_double(51822367833714164, -109) /* 7.9844999999999994e-017 */, \"7984499999999999\", -32);\n check_double(make_double(66840152193508133, -172) /* 1.1165499999999999e-035 */, \"11165499999999999\", -51);\n check_double(make_double(55111239245584393, -138) /* 1.581615e-025 */, \"1581615\", -31);\n check_double(make_double(71704866733321482, -112) /* 1.3809855e-017 */, \"13809855\", -24);\n check_double(make_double(67160949328233173, -142) /* 1.2046404499999999e-026 */, \"12046404499999999\", -42);\n check_double(make_double(53237141308040189, -152) /* 9.3251405449999991e-030 */, \"9325140544999999\", -45);\n check_double(make_double(62785329394975786, -112) /* 1.2092014595e-017 */, \"12092014595\", -27);\n check_double(make_double(48367680154689523, -77) /* 3.2007045838499998e-007 */, \"320070458385\", -18);\n check_double(make_double(42552223180606797, -102) /* 8.391946324354999e-015 */, \"8391946324354999\", -30);\n check_double(make_double(63626356173011241, -112) /* 1.2253990460585e-017 */, \"12253990460585\", -30);\n check_double(make_double(43566388595783643, -99) /* 6.8735641489760495e-014 */, \"687356414897605\", -28);\n check_double(make_double(54512669636675272, -159) /* 7.459816430480385e-032 */, \"7459816430480385\", -47);\n check_double(make_double(52306490527514614, -167) /* 2.7960588398142552e-034 */, \"2796058839814255\", -49);\n check_double(make_double(52306490527514614, -168) /* 1.3980294199071276e-034 */, \"13980294199071276\", -50);\n check_double(make_double(41024721590449423, -89) /* 6.6279012373057359e-011 */, \"6627901237305736\", -26);\n check_double(make_double(37664020415894738, -132) /* 6.9177880043968072e-024 */, \"6917788004396807\", -39);\n check_double(make_double(37549883692866294, -93) /* 3.7915693108349708e-012 */, \"3791569310834971\", -27);\n check_double(make_double(69124110374399839, -104) /* 3.4080817676591365e-015 */, \"34080817676591365\", -31);\n check_double(make_double(69124110374399839, -105) /* 1.7040408838295683e-015 */, \"17040408838295683\", -31);\n\n // Table 21: Stress Inputs for Converting 56-bit Binary to Decimal, > 1/2 ULP\n check_double(make_double(49517601571415211, -94) /* 2.4999999999999998e-012 */, \"25\", -13);\n check_double(make_double(49517601571415211, -95) /* 1.2499999999999999e-012 */, \"125\", -14);\n check_double(make_double(54390733528642804, -133) /* 4.9949999999999996e-024 */, \"49949999999999996\", -40); // shortest: 4995e-27\n check_double(make_double(71805402319113924, -157) /* 3.9304999999999998e-031 */, \"39304999999999998\", -47); // shortest: 39305e-35\n check_double(make_double(40435277969631694, -179) /* 5.2770499999999992e-038 */, \"5277049999999999\", -53);\n check_double(make_double(57241991568619049, -165) /* 1.223955e-033 */, \"1223955\", -39);\n check_double(make_double(65224162876242886, +58) /* 1.8799584999999998e+034 */, \"18799584999999998\", 18);\n check_double(make_double(70173376848895368, -138) /* 2.01387715e-025 */, \"201387715\", -33);\n check_double(make_double(37072848117383207, -99) /* 5.8490641049999989e-014 */, \"5849064104999999\", -29);\n check_double(make_double(56845051585389697, -176) /* 5.9349003054999999e-037 */, \"59349003055\", -47);\n check_double(make_double(54791673366936431, -145) /* 1.2284718039499998e-027 */, \"12284718039499998\", -43);\n check_double(make_double(66800318669106231, -169) /* 8.9270767180849991e-035 */, \"8927076718084999\", -50);\n check_double(make_double(66800318669106231, -170) /* 4.4635383590424995e-035 */, \"44635383590424995\", -51);\n check_double(make_double(66574323440112438, -119) /* 1.0016990862549499e-019 */, \"10016990862549499\", -35);\n check_double(make_double(65645179969330963, -173) /* 5.4829412628024647e-036 */, \"5482941262802465\", -51);\n check_double(make_double(61847254334681076, -109) /* 9.5290783281036439e-017 */, \"9529078328103644\", -32);\n check_double(make_double(39990712921393606, -145) /* 8.9662279366405553e-028 */, \"8966227936640555\", -43);\n check_double(make_double(59292318184400283, -149) /* 8.3086234418058538e-029 */, \"8308623441805854\", -44);\n check_double(make_double(69116558615326153, -143) /* 6.1985873566126555e-027 */, \"61985873566126555\", -43);\n check_double(make_double(69116558615326153, -144) /* 3.0992936783063277e-027 */, \"30992936783063277\", -43);\n check_double(make_double(39462549494468513, -152) /* 6.9123512506176015e-030 */, \"6912351250617602\", -45);\n check_double(make_double(39462549494468513, -153) /* 3.4561756253088008e-030 */, \"3456175625308801\", -45);\n }\n}\n\nTEST_CASE(\"formatting\")\n{\n SECTION(\"single precision\")\n {\n auto check_float = [](float number, const std::string & expected)\n {\n std::array buf{};\n char* end = nlohmann::detail::to_chars(buf.data(), buf.data() + 32, number); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)\n const std::string actual(buf.data(), end);\n\n CHECK(actual == expected);\n };\n // %.9g\n check_float( -1.2345e-22f, \"-1.2345e-22\" ); // -1.23450004e-22\n check_float( -1.2345e-21f, \"-1.2345e-21\" ); // -1.23450002e-21\n check_float( -1.2345e-20f, \"-1.2345e-20\" ); // -1.23450002e-20\n check_float( -1.2345e-19f, \"-1.2345e-19\" ); // -1.23449999e-19\n check_float( -1.2345e-18f, \"-1.2345e-18\" ); // -1.23449996e-18\n check_float( -1.2345e-17f, \"-1.2345e-17\" ); // -1.23449998e-17\n check_float( -1.2345e-16f, \"-1.2345e-16\" ); // -1.23449996e-16\n check_float( -1.2345e-15f, \"-1.2345e-15\" ); // -1.23450002e-15\n check_float( -1.2345e-14f, \"-1.2345e-14\" ); // -1.23450004e-14\n check_float( -1.2345e-13f, \"-1.2345e-13\" ); // -1.23449997e-13\n check_float( -1.2345e-12f, \"-1.2345e-12\" ); // -1.23450002e-12\n check_float( -1.2345e-11f, \"-1.2345e-11\" ); // -1.2345e-11\n check_float( -1.2345e-10f, \"-1.2345e-10\" ); // -1.2345e-10\n check_float( -1.2345e-9f, \"-1.2345e-09\" ); // -1.23449995e-09\n check_float( -1.2345e-8f, \"-1.2345e-08\" ); // -1.23449997e-08\n check_float( -1.2345e-7f, \"-1.2345e-07\" ); // -1.23449993e-07\n check_float( -1.2345e-6f, \"-1.2345e-06\" ); // -1.23450002e-06\n check_float( -1.2345e-5f, \"-1.2345e-05\" ); // -1.2345e-05\n check_float( -1.2345e-4f, \"-0.00012345\" ); // -0.000123449994\n check_float( -1.2345e-3f, \"-0.0012345\" ); // -0.00123449997\n check_float( -1.2345e-2f, \"-0.012345\" ); // -0.0123450002\n check_float( -1.2345e-1f, \"-0.12345\" ); // -0.123450004\n check_float( -0.0f, \"-0.0\" ); // -0\n check_float( 0.0f, \"0.0\" ); // 0\n check_float( 1.2345e+0f, \"1.2345\" ); // 1.23450005\n check_float( 1.2345e+1f, \"12.345\" ); // 12.3450003\n check_float( 1.2345e+2f, \"123.45\" ); // 123.449997\n check_float( 1.2345e+3f, \"1234.5\" ); // 1234.5\n check_float( 1.2345e+4f, \"12345.0\" ); // 12345\n check_float( 1.2345e+5f, \"123450.0\" ); // 123450\n check_float( 1.2345e+6f, \"1.2345e+06\" ); // 1234500\n check_float( 1.2345e+7f, \"1.2345e+07\" ); // 12345000\n check_float( 1.2345e+8f, \"1.2345e+08\" ); // 123450000\n check_float( 1.2345e+9f, \"1.2345e+09\" ); // 1.23449997e+09\n check_float( 1.2345e+10f, \"1.2345e+10\" ); // 1.23449999e+10\n check_float( 1.2345e+11f, \"1.2345e+11\" ); // 1.23449999e+11\n check_float( 1.2345e+12f, \"1.2345e+12\" ); // 1.23450006e+12\n check_float( 1.2345e+13f, \"1.2345e+13\" ); // 1.23449995e+13\n check_float( 1.2345e+14f, \"1.2345e+14\" ); // 1.23450002e+14\n check_float( 1.2345e+15f, \"1.2345e+15\" ); // 1.23450003e+15\n check_float( 1.2345e+16f, \"1.2345e+16\" ); // 1.23449998e+16\n check_float( 1.2345e+17f, \"1.2345e+17\" ); // 1.23449996e+17\n check_float( 1.2345e+18f, \"1.2345e+18\" ); // 1.23450004e+18\n check_float( 1.2345e+19f, \"1.2345e+19\" ); // 1.23449999e+19\n check_float( 1.2345e+20f, \"1.2345e+20\" ); // 1.23449999e+20\n check_float( 1.2345e+21f, \"1.2345e+21\" ); // 1.23449999e+21\n check_float( 1.2345e+22f, \"1.2345e+22\" ); // 1.23450005e+22\n }\n\n SECTION(\"double precision\")\n {\n auto check_double = [](double number, const std::string & expected)\n {\n std::array buf{};\n char* end = nlohmann::detail::to_chars(buf.data(), buf.data() + 32, number); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)\n const std::string actual(buf.data(), end);\n\n CHECK(actual == expected);\n };\n // dtoa %.15g %.17g shortest\n check_double( -1.2345e-22, \"-1.2345e-22\" ); // -1.2345e-22 -1.2345000000000001e-22 -1.2345e-22\n check_double( -1.2345e-21, \"-1.2345e-21\" ); // -1.2345e-21 -1.2345000000000001e-21 -1.2345e-21\n check_double( -1.2345e-20, \"-1.2345e-20\" ); // -1.2345e-20 -1.2345e-20 -1.2345e-20\n check_double( -1.2345e-19, \"-1.2345e-19\" ); // -1.2345e-19 -1.2345000000000001e-19 -1.2345e-19\n check_double( -1.2345e-18, \"-1.2345e-18\" ); // -1.2345e-18 -1.2345000000000001e-18 -1.2345e-18\n check_double( -1.2345e-17, \"-1.2345e-17\" ); // -1.2345e-17 -1.2345e-17 -1.2345e-17\n check_double( -1.2345e-16, \"-1.2345e-16\" ); // -1.2345e-16 -1.2344999999999999e-16 -1.2345e-16\n check_double( -1.2345e-15, \"-1.2345e-15\" ); // -1.2345e-15 -1.2345e-15 -1.2345e-15\n check_double( -1.2345e-14, \"-1.2345e-14\" ); // -1.2345e-14 -1.2345e-14 -1.2345e-14\n check_double( -1.2345e-13, \"-1.2345e-13\" ); // -1.2345e-13 -1.2344999999999999e-13 -1.2345e-13\n check_double( -1.2345e-12, \"-1.2345e-12\" ); // -1.2345e-12 -1.2345e-12 -1.2345e-12\n check_double( -1.2345e-11, \"-1.2345e-11\" ); // -1.2345e-11 -1.2345e-11 -1.2345e-11\n check_double( -1.2345e-10, \"-1.2345e-10\" ); // -1.2345e-10 -1.2345e-10 -1.2345e-10\n check_double( -1.2345e-9, \"-1.2345e-09\" ); // -1.2345e-09 -1.2345e-09 -1.2345e-9\n check_double( -1.2345e-8, \"-1.2345e-08\" ); // -1.2345e-08 -1.2345000000000001e-08 -1.2345e-8\n check_double( -1.2345e-7, \"-1.2345e-07\" ); // -1.2345e-07 -1.2345000000000001e-07 -1.2345e-7\n check_double( -1.2345e-6, \"-1.2345e-06\" ); // -1.2345e-06 -1.2345e-06 -1.2345e-6\n check_double( -1.2345e-5, \"-1.2345e-05\" ); // -1.2345e-05 -1.2345e-05 -1.2345e-5\n check_double( -1.2345e-4, \"-0.00012345\" ); // -0.00012345 -0.00012344999999999999 -0.00012345\n check_double( -1.2345e-3, \"-0.0012345\" ); // -0.0012345 -0.0012344999999999999 -0.0012345\n check_double( -1.2345e-2, \"-0.012345\" ); // -0.012345 -0.012345 -0.012345\n check_double( -1.2345e-1, \"-0.12345\" ); // -0.12345 -0.12345 -0.12345\n check_double( -0.0, \"-0.0\" ); // -0 -0 -0\n check_double( 0.0, \"0.0\" ); // 0 0 0\n check_double( 1.2345e+0, \"1.2345\" ); // 1.2345 1.2344999999999999 1.2345\n check_double( 1.2345e+1, \"12.345\" ); // 12.345 12.345000000000001 12.345\n check_double( 1.2345e+2, \"123.45\" ); // 123.45 123.45 123.45\n check_double( 1.2345e+3, \"1234.5\" ); // 1234.5 1234.5 1234.5\n check_double( 1.2345e+4, \"12345.0\" ); // 12345 12345 12345\n check_double( 1.2345e+5, \"123450.0\" ); // 123450 123450 123450\n check_double( 1.2345e+6, \"1234500.0\" ); // 1234500 1234500 1234500\n check_double( 1.2345e+7, \"12345000.0\" ); // 12345000 12345000 12345000\n check_double( 1.2345e+8, \"123450000.0\" ); // 123450000 123450000 123450000\n check_double( 1.2345e+9, \"1234500000.0\" ); // 1234500000 1234500000 1234500000\n check_double( 1.2345e+10, \"12345000000.0\" ); // 12345000000 12345000000 12345000000\n check_double( 1.2345e+11, \"123450000000.0\" ); // 123450000000 123450000000 123450000000\n check_double( 1.2345e+12, \"1234500000000.0\" ); // 1234500000000 1234500000000 1234500000000\n check_double( 1.2345e+13, \"12345000000000.0\" ); // 12345000000000 12345000000000 12345000000000\n check_double( 1.2345e+14, \"123450000000000.0\" ); // 123450000000000 123450000000000 123450000000000\n check_double( 1.2345e+15, \"1.2345e+15\" ); // 1.2345e+15 1234500000000000 1.2345e15\n check_double( 1.2345e+16, \"1.2345e+16\" ); // 1.2345e+16 12345000000000000 1.2345e16\n check_double( 1.2345e+17, \"1.2345e+17\" ); // 1.2345e+17 1.2345e+17 1.2345e17\n check_double( 1.2345e+18, \"1.2345e+18\" ); // 1.2345e+18 1.2345e+18 1.2345e18\n check_double( 1.2345e+19, \"1.2345e+19\" ); // 1.2345e+19 1.2345e+19 1.2345e19\n check_double( 1.2345e+20, \"1.2345e+20\" ); // 1.2345e+20 1.2345e+20 1.2345e20\n check_double( 1.2345e+21, \"1.2344999999999999e+21\" ); // 1.2345e+21 1.2344999999999999e+21 1.2345e21\n check_double( 1.2345e+22, \"1.2345e+22\" ); // 1.2345e+22 1.2345e+22 1.2345e22\n }\n\n SECTION(\"integer\")\n {\n auto check_integer = [](std::int64_t number, const std::string & expected)\n {\n const nlohmann::json j = number;\n CHECK(j.dump() == expected);\n };\n\n // edge cases\n check_integer(INT64_MIN, \"-9223372036854775808\");\n check_integer(INT64_MAX, \"9223372036854775807\");\n\n // few random big integers\n check_integer(-3456789012345678901LL, \"-3456789012345678901\");\n check_integer(3456789012345678901LL, \"3456789012345678901\");\n check_integer(-5678901234567890123LL, \"-5678901234567890123\");\n check_integer(5678901234567890123LL, \"5678901234567890123\");\n\n // integers with various digit counts\n check_integer(-1000000000000000000LL, \"-1000000000000000000\");\n check_integer(-100000000000000000LL, \"-100000000000000000\");\n check_integer(-10000000000000000LL, \"-10000000000000000\");\n check_integer(-1000000000000000LL, \"-1000000000000000\");\n check_integer(-100000000000000LL, \"-100000000000000\");\n check_integer(-10000000000000LL, \"-10000000000000\");\n check_integer(-1000000000000LL, \"-1000000000000\");\n check_integer(-100000000000LL, \"-100000000000\");\n check_integer(-10000000000LL, \"-10000000000\");\n check_integer(-1000000000LL, \"-1000000000\");\n check_integer(-100000000LL, \"-100000000\");\n check_integer(-10000000LL, \"-10000000\");\n check_integer(-1000000LL, \"-1000000\");\n check_integer(-100000LL, \"-100000\");\n check_integer(-10000LL, \"-10000\");\n check_integer(-1000LL, \"-1000\");\n check_integer(-100LL, \"-100\");\n check_integer(-10LL, \"-10\");\n check_integer(-1LL, \"-1\");\n check_integer(0, \"0\");\n check_integer(1LL, \"1\");\n check_integer(10LL, \"10\");\n check_integer(100LL, \"100\");\n check_integer(1000LL, \"1000\");\n check_integer(10000LL, \"10000\");\n check_integer(100000LL, \"100000\");\n check_integer(1000000LL, \"1000000\");\n check_integer(10000000LL, \"10000000\");\n check_integer(100000000LL, \"100000000\");\n check_integer(1000000000LL, \"1000000000\");\n check_integer(10000000000LL, \"10000000000\");\n check_integer(100000000000LL, \"100000000000\");\n check_integer(1000000000000LL, \"1000000000000\");\n check_integer(10000000000000LL, \"10000000000000\");\n check_integer(100000000000000LL, \"100000000000000\");\n check_integer(1000000000000000LL, \"1000000000000000\");\n check_integer(10000000000000000LL, \"10000000000000000\");\n check_integer(100000000000000000LL, \"100000000000000000\");\n check_integer(1000000000000000000LL, \"1000000000000000000\");\n }\n}", "messages": null, "tools": null} {"id": "6fda2213cd326d74", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/lib/src/main.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 604, "sha256": "c4569e6b8c14240f4f1eeb6ca63e1ad7136db3c927c31d935e87f9069bc2cad2", "text": "export default /* @__PURE__ */ Object.assign(function myLib(sel) {\n // Force esbuild spread helpers (https://github.com/evanw/esbuild/issues/951)\n console.log({ ...'foo' })\n\n document.querySelector(sel).textContent = 'It works'\n\n // Env vars should not be replaced\n console.log(process.env.NODE_ENV)\n\n // make sure umd helper has been moved to the right position\n console.log(`amd function(){ \"use strict\"; }`)\n\n // eslint-disable-next-line no-debugger\n debugger\n})\n\n// For triggering unhandled global esbuild helpers in previous regex-based implementation for injection\n;(function () {})()?.foo", "messages": null, "tools": null} {"id": "7022d14bda700658", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/ssr-html/server.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 3035, "sha256": "7a583e5866428b41c6c02e1864d55f1cf5b9153eb612d02d4399c44e9f3c986d", "text": "import fs from 'node:fs'\nimport path from 'node:path'\nimport express from 'express'\n\nconst isTest = process.env.VITEST\n\nconst DYNAMIC_SCRIPTS = `\n \n \n`\n\nconst DYNAMIC_STYLES = `\n \n`\n\nexport async function createServer(\n root = process.cwd(),\n hmrPort,\n customLogger,\n) {\n const resolve = (p) => path.resolve(import.meta.dirname, p)\n\n const app = express()\n\n /**\n * @type {import('vite').ViteDevServer}\n */\n const vite = await (\n await import('vite')\n ).createServer({\n root,\n logLevel: isTest ? 'error' : 'info',\n server: {\n middlewareMode: true,\n watch: {\n // During tests we edit the files too fast and sometimes chokidar\n // misses change events, so enforce polling for consistency\n usePolling: true,\n interval: 100,\n },\n hmr: {\n port: hmrPort,\n },\n },\n appType: 'custom',\n customLogger,\n plugins: [\n {\n name: 'virtual-file',\n resolveId(id) {\n if (id === 'virtual:file') {\n return '\\0virtual:file'\n }\n },\n load(id) {\n if (id === '\\0virtual:file') {\n return 'import { virtual } from \"/src/importedVirtual.js\"; export { virtual };'\n }\n },\n },\n ],\n })\n // use vite's connect instance as middleware\n app.use(vite.middlewares)\n\n app.use('*all', async (req, res, next) => {\n try {\n let [url] = req.originalUrl.split('?')\n\n if (url === '/trailing-slash/dir/') {\n const template = fs.readFileSync(resolve(`.${url}index.html`), 'utf-8')\n const html = await vite.transformIndexHtml(url, template)\n return res.status(200).set({ 'Content-Type': 'text/html' }).end(html)\n }\n\n if (url.endsWith('/')) url += 'index.html'\n\n if (url.startsWith('/favicon.ico')) {\n return res.status(404).end('404')\n }\n if (url.startsWith('/@id/__x00__')) {\n return next()\n }\n\n const htmlLoc = resolve(`.${url}`)\n let template = fs.readFileSync(htmlLoc, 'utf-8')\n\n template = template.replace(\n '',\n `${DYNAMIC_SCRIPTS}${DYNAMIC_STYLES}`,\n )\n\n // Force calling transformIndexHtml with url === '/', to simulate\n // usage by ecosystem that was recommended in the SSR documentation\n // as `const url = req.originalUrl`\n const html = await vite.transformIndexHtml('/', template)\n\n res.status(200).set({ 'Content-Type': 'text/html' }).end(html)\n } catch (e) {\n vite && vite.ssrFixStacktrace(e)\n console.log(e.stack)\n res.status(500).end(e.stack)\n }\n })\n\n return { app, vite }\n}\n\nif (!isTest) {\n createServer().then(({ app }) =>\n app.listen(5173, () => {\n console.log('http://localhost:5173')\n }),\n )\n}", "messages": null, "tools": null} {"id": "70247f16f968988c", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/hmr-full-bundle-mode/worker-nested-outer.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 298, "sha256": "f2530714c22f49587d663f827678ee8e53f94190b2bca96ef76e0e55e5022de0", "text": "const inner = new Worker(new URL('./worker-nested-inner.js', import.meta.url), {\n type: 'module',\n})\n\nself.onmessage = () => {\n inner.postMessage('ping')\n}\ninner.onmessage = (e) => {\n self.postMessage(`nested-outer+${e.data}`)\n}\ninner.onerror = () => {\n self.postMessage('nested-inner-error')\n}", "messages": null, "tools": null} {"id": "7082e654c7566b9a", "category": "code", "domain": "code", "source": "flask", "license": "BSD-3-Clause", "license_url": "https://spdx.org/licenses/BSD-3-Clause.html", "path": "src/flask/json/tag.py", "lang": "python", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/pallets/flask", "commit": "6a2f545bfd8ed31e19066a299296917e034aca58", "collector": "tools/harvest.py"}, "chars": 9280, "sha256": "a6c38a179040b7e1116b2d0674f6693f5671ecc5dd5983f5a6b87e3eea396fd2", "text": "\"\"\"\nTagged JSON\n~~~~~~~~~~~\n\nA compact representation for lossless serialization of non-standard JSON\ntypes. :class:`~flask.sessions.SecureCookieSessionInterface` uses this\nto serialize the session data, but it may be useful in other places. It\ncan be extended to support other types.\n\n.. autoclass:: TaggedJSONSerializer\n :members:\n\n.. autoclass:: JSONTag\n :members:\n\nLet's see an example that adds support for\n:class:`~collections.OrderedDict`. Dicts don't have an order in JSON, so\nto handle this we will dump the items as a list of ``[key, value]``\npairs. Subclass :class:`JSONTag` and give it the new key ``' od'`` to\nidentify the type. The session serializer processes dicts first, so\ninsert the new tag at the front of the order since ``OrderedDict`` must\nbe processed before ``dict``.\n\n.. code-block:: python\n\n from flask.json.tag import JSONTag\n\n class TagOrderedDict(JSONTag):\n __slots__ = ('serializer',)\n key = ' od'\n\n def check(self, value):\n return isinstance(value, OrderedDict)\n\n def to_json(self, value):\n return [[k, self.serializer.tag(v)] for k, v in iteritems(value)]\n\n def to_python(self, value):\n return OrderedDict(value)\n\n app.session_interface.serializer.register(TagOrderedDict, index=0)\n\"\"\"\n\nfrom __future__ import annotations\n\nimport typing as t\nfrom base64 import b64decode\nfrom base64 import b64encode\nfrom datetime import datetime\nfrom uuid import UUID\n\nfrom markupsafe import Markup\nfrom werkzeug.http import http_date\nfrom werkzeug.http import parse_date\n\nfrom ..json import dumps\nfrom ..json import loads\n\n\nclass JSONTag:\n \"\"\"Base class for defining type tags for :class:`TaggedJSONSerializer`.\"\"\"\n\n __slots__ = (\"serializer\",)\n\n #: The tag to mark the serialized object with. If empty, this tag is\n #: only used as an intermediate step during tagging.\n key: str = \"\"\n\n def __init__(self, serializer: TaggedJSONSerializer) -> None:\n \"\"\"Create a tagger for the given serializer.\"\"\"\n self.serializer = serializer\n\n def check(self, value: t.Any) -> bool:\n \"\"\"Check if the given value should be tagged by this tag.\"\"\"\n raise NotImplementedError\n\n def to_json(self, value: t.Any) -> t.Any:\n \"\"\"Convert the Python object to an object that is a valid JSON type.\n The tag will be added later.\"\"\"\n raise NotImplementedError\n\n def to_python(self, value: t.Any) -> t.Any:\n \"\"\"Convert the JSON representation back to the correct type. The tag\n will already be removed.\"\"\"\n raise NotImplementedError\n\n def tag(self, value: t.Any) -> dict[str, t.Any]:\n \"\"\"Convert the value to a valid JSON type and add the tag structure\n around it.\"\"\"\n return {self.key: self.to_json(value)}\n\n\nclass TagDict(JSONTag):\n \"\"\"Tag for 1-item dicts whose only key matches a registered tag.\n\n Internally, the dict key is suffixed with `__`, and the suffix is removed\n when deserializing.\n \"\"\"\n\n __slots__ = ()\n key = \" di\"\n\n def check(self, value: t.Any) -> bool:\n return (\n isinstance(value, dict)\n and len(value) == 1\n and next(iter(value)) in self.serializer.tags\n )\n\n def to_json(self, value: t.Any) -> t.Any:\n key = next(iter(value))\n return {f\"{key}__\": self.serializer.tag(value[key])}\n\n def to_python(self, value: t.Any) -> t.Any:\n key = next(iter(value))\n return {key[:-2]: value[key]}\n\n\nclass PassDict(JSONTag):\n __slots__ = ()\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, dict)\n\n def to_json(self, value: t.Any) -> t.Any:\n # JSON objects may only have string keys, so don't bother tagging the\n # key here.\n return {k: self.serializer.tag(v) for k, v in value.items()}\n\n tag = to_json\n\n\nclass TagTuple(JSONTag):\n __slots__ = ()\n key = \" t\"\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, tuple)\n\n def to_json(self, value: t.Any) -> t.Any:\n return [self.serializer.tag(item) for item in value]\n\n def to_python(self, value: t.Any) -> t.Any:\n return tuple(value)\n\n\nclass PassList(JSONTag):\n __slots__ = ()\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, list)\n\n def to_json(self, value: t.Any) -> t.Any:\n return [self.serializer.tag(item) for item in value]\n\n tag = to_json\n\n\nclass TagBytes(JSONTag):\n __slots__ = ()\n key = \" b\"\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, bytes)\n\n def to_json(self, value: t.Any) -> t.Any:\n return b64encode(value).decode(\"ascii\")\n\n def to_python(self, value: t.Any) -> t.Any:\n return b64decode(value)\n\n\nclass TagMarkup(JSONTag):\n \"\"\"Serialize anything matching the :class:`~markupsafe.Markup` API by\n having a ``__html__`` method to the result of that method. Always\n deserializes to an instance of :class:`~markupsafe.Markup`.\"\"\"\n\n __slots__ = ()\n key = \" m\"\n\n def check(self, value: t.Any) -> bool:\n return callable(getattr(value, \"__html__\", None))\n\n def to_json(self, value: t.Any) -> t.Any:\n return str(value.__html__())\n\n def to_python(self, value: t.Any) -> t.Any:\n return Markup(value)\n\n\nclass TagUUID(JSONTag):\n __slots__ = ()\n key = \" u\"\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, UUID)\n\n def to_json(self, value: t.Any) -> t.Any:\n return value.hex\n\n def to_python(self, value: t.Any) -> t.Any:\n return UUID(value)\n\n\nclass TagDateTime(JSONTag):\n __slots__ = ()\n key = \" d\"\n\n def check(self, value: t.Any) -> bool:\n return isinstance(value, datetime)\n\n def to_json(self, value: t.Any) -> t.Any:\n return http_date(value)\n\n def to_python(self, value: t.Any) -> t.Any:\n return parse_date(value)\n\n\nclass TaggedJSONSerializer:\n \"\"\"Serializer that uses a tag system to compactly represent objects that\n are not JSON types. Passed as the intermediate serializer to\n :class:`itsdangerous.Serializer`.\n\n The following extra types are supported:\n\n * :class:`dict`\n * :class:`tuple`\n * :class:`bytes`\n * :class:`~markupsafe.Markup`\n * :class:`~uuid.UUID`\n * :class:`~datetime.datetime`\n \"\"\"\n\n __slots__ = (\"tags\", \"order\")\n\n #: Tag classes to bind when creating the serializer. Other tags can be\n #: added later using :meth:`~register`.\n default_tags = [\n TagDict,\n PassDict,\n TagTuple,\n PassList,\n TagBytes,\n TagMarkup,\n TagUUID,\n TagDateTime,\n ]\n\n def __init__(self) -> None:\n self.tags: dict[str, JSONTag] = {}\n self.order: list[JSONTag] = []\n\n for cls in self.default_tags:\n self.register(cls)\n\n def register(\n self,\n tag_class: type[JSONTag],\n force: bool = False,\n index: int | None = None,\n ) -> None:\n \"\"\"Register a new tag with this serializer.\n\n :param tag_class: tag class to register. Will be instantiated with this\n serializer instance.\n :param force: overwrite an existing tag. If false (default), a\n :exc:`KeyError` is raised.\n :param index: index to insert the new tag in the tag order. Useful when\n the new tag is a special case of an existing tag. If ``None``\n (default), the tag is appended to the end of the order.\n\n :raise KeyError: if the tag key is already registered and ``force`` is\n not true.\n \"\"\"\n tag = tag_class(self)\n key = tag.key\n\n if key:\n if not force and key in self.tags:\n raise KeyError(f\"Tag '{key}' is already registered.\")\n\n self.tags[key] = tag\n\n if index is None:\n self.order.append(tag)\n else:\n self.order.insert(index, tag)\n\n def tag(self, value: t.Any) -> t.Any:\n \"\"\"Convert a value to a tagged representation if necessary.\"\"\"\n for tag in self.order:\n if tag.check(value):\n return tag.tag(value)\n\n return value\n\n def untag(self, value: dict[str, t.Any]) -> t.Any:\n \"\"\"Convert a tagged representation back to the original type.\"\"\"\n if len(value) != 1:\n return value\n\n key = next(iter(value))\n\n if key not in self.tags:\n return value\n\n return self.tags[key].to_python(value[key])\n\n def _untag_scan(self, value: t.Any) -> t.Any:\n if isinstance(value, dict):\n # untag each item recursively\n value = {k: self._untag_scan(v) for k, v in value.items()}\n # untag the dict itself\n value = self.untag(value)\n elif isinstance(value, list):\n # untag each item recursively\n value = [self._untag_scan(item) for item in value]\n\n return value\n\n def dumps(self, value: t.Any) -> str:\n \"\"\"Tag the value and dump it to a compact JSON string.\"\"\"\n return dumps(self.tag(value), separators=(\",\", \":\"))\n\n def loads(self, value: str) -> t.Any:\n \"\"\"Load data from a JSON string and deserialized any tagged objects.\"\"\"\n return self._untag_scan(loads(value))", "messages": null, "tools": null} {"id": "709286ffd7f39212", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/multiple-entrypoints/entrypoints/a15.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 414, "sha256": "cbe1f3b434081bc71f06e20f745d082aff69a0d750430abc5f778a54b8ce92b7", "text": "import a16 from './a16'\nimport a17 from './a17'\nimport a18 from './a18'\nimport a19 from './a19'\nimport a20 from './a20'\nimport a21 from './a21'\nimport a22 from './a22'\nimport a23 from './a23'\nimport a24 from './a24'\n\nexport const that = () => import('./a14.js')\n\nexport function other() {\n return a16() + a17() + a18() + a19() + a20() + a21() + a22() + a23() + a24()\n}\n\nexport default function () {\n return 123\n}", "messages": null, "tools": null} {"id": "70994405b9d91028", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/is_number_unsigned.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 1050, "sha256": "55ff6676d355fbb9ac300c490c2594209adbdcc653b932c4b5468b98f67617e1", "text": "#include \n#include \n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_number_unsigned()\n std::cout << std::boolalpha;\n std::cout << j_null.is_number_unsigned() << '\\n';\n std::cout << j_boolean.is_number_unsigned() << '\\n';\n std::cout << j_number_integer.is_number_unsigned() << '\\n';\n std::cout << j_number_unsigned_integer.is_number_unsigned() << '\\n';\n std::cout << j_number_float.is_number_unsigned() << '\\n';\n std::cout << j_object.is_number_unsigned() << '\\n';\n std::cout << j_array.is_number_unsigned() << '\\n';\n std::cout << j_string.is_number_unsigned() << '\\n';\n std::cout << j_binary.is_number_unsigned() << '\\n';\n}", "messages": null, "tools": null} {"id": "70cc575e04f44266", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/abi/diag/diag.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 1083, "sha256": "710ade6b56090ceb44600be469d20d62204656b5c2bf6e24b66ed4ecbb39b84a", "text": "// __ _____ _____ _____\n// __| | __| | | | JSON for Modern C++ (supporting code)\n// | | |__ | | | | | | version 3.12.0\n// |_____|_____|_____|_|___| https://github.com/nlohmann/json\n//\n// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann \n// SPDX-License-Identifier: MIT\n\n#include \"doctest_compatibility.h\"\n\n#include \"diag.hpp\"\n\nTEST_CASE(\"ABI compatible diagnostics\")\n{\n SECTION(\"basic_json size\")\n {\n // basic_json with diagnostics is larger because of added data members\n CHECK(json_sizeof_diag_on() == json_sizeof_diag_on_explicit());\n CHECK(json_sizeof_diag_off() == json_sizeof_diag_off_explicit());\n CHECK(json_sizeof_diag_on() > json_sizeof_diag_off());\n }\n\n SECTION(\"basic_json at\")\n {\n // accessing a nonexistent key throws different exception with diagnostics\n CHECK_THROWS_WITH(json_at_diag_on(), \"[json.exception.out_of_range.403] (/foo) key 'bar' not found\");\n CHECK_THROWS_WITH(json_at_diag_off(), \"[json.exception.out_of_range.403] key 'bar' not found\");\n }\n}", "messages": null, "tools": null} {"id": "70ddf9e00231a276", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/sax_parse.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 3318, "sha256": "d47d64e73de331ca04562123977ef526ccce975ea78d84c3ecef9b8ace663a22", "text": "#include \n#include \n#include \n#include \n\nusing json = nlohmann::json;\n\n// a simple event consumer that collects string representations of the passed\n// values; note inheriting from json::json_sax_t is not required, but can\n// help not to forget a required function\nclass sax_event_consumer : public json::json_sax_t\n{\n public:\n std::vector events;\n\n bool null() override\n {\n events.push_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val) override\n {\n events.push_back(\"boolean(val=\" + std::string(val ? \"true\" : \"false\") + \")\");\n return true;\n }\n\n bool number_integer(number_integer_t val) override\n {\n events.push_back(\"number_integer(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(number_unsigned_t val) override\n {\n events.push_back(\"number_unsigned(val=\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(number_float_t val, const string_t& s) override\n {\n events.push_back(\"number_float(val=\" + std::to_string(val) + \", s=\" + s + \")\");\n return true;\n }\n\n bool string(string_t& val) override\n {\n events.push_back(\"string(val=\" + val + \")\");\n return true;\n }\n\n bool start_object(std::size_t elements) override\n {\n events.push_back(\"start_object(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_object() override\n {\n events.push_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements) override\n {\n events.push_back(\"start_array(elements=\" + std::to_string(elements) + \")\");\n return true;\n }\n\n bool end_array() override\n {\n events.push_back(\"end_array()\");\n return true;\n }\n\n bool key(string_t& val) override\n {\n events.push_back(\"key(val=\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val) override\n {\n events.push_back(\"binary(val=[...])\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override\n {\n events.push_back(\"parse_error(position=\" + std::to_string(position) + \", last_token=\" + last_token + \",\\n ex=\" + std::string(ex.what()) + \")\");\n return false;\n }\n};\n\nint main()\n{\n // a JSON text\n auto text = R\"(\n {\n \"Image\": {\n \"Width\": 800,\n \"Height\": 600,\n \"Title\": \"View from 15th Floor\",\n \"Thumbnail\": {\n \"Url\": \"http://www.example.com/image/481989943\",\n \"Height\": 125,\n \"Width\": 100\n },\n \"Animated\" : false,\n \"IDs\": [116, 943, 234, -38793],\n \"DeletionDate\": null,\n \"Distance\": 12.723374634\n }\n }]\n )\";\n\n // create a SAX event consumer object\n sax_event_consumer sec;\n\n // parse JSON\n bool result = json::sax_parse(text, &sec);\n\n // output the recorded events\n for (auto& event : sec.events)\n {\n std::cout << event << \"\\n\";\n }\n\n // output the result of sax_parse\n std::cout << \"\\nresult: \" << std::boolalpha << result << std::endl;\n}", "messages": null, "tools": null} {"id": "7164b9a7ce2d81bc", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/alias/__tests__/alias.spec.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 1522, "sha256": "6edcddbb87fac884613f025dd3f58a229dbe0643d3b968b7aeb46614669f4685", "text": "import { expect, test } from 'vitest'\nimport { editFile, getColor, isBuild, page } from '~utils'\n\ntest('fs', async () => {\n expect(await page.textContent('.fs')).toMatch('[success] alias to fs path')\n})\n\ntest('fs directory', async () => {\n expect(await page.textContent('.fs-dir')).toMatch(\n '[success] alias to directory',\n )\n})\n\ntest('regex', async () => {\n expect(await page.textContent('.regex')).toMatch(\n '[success] alias to directory via regex',\n )\n})\n\ntest('dependency', async () => {\n expect(await page.textContent('.dep')).toMatch('[success] out of root')\n})\n\ntest('js via script src', async () => {\n expect(await page.textContent('.from-script-src')).toMatch(\n '[success] from script src',\n )\n})\n\ntest('css via link', async () => {\n expect(await getColor('body')).toBe('grey')\n if (isBuild) return\n editFile('dir/test.css', (code) => code.replace('grey', 'red'))\n await expect.poll(() => getColor('body')).toBe('red')\n})\n\ntest('optimized dep', async () => {\n expect(await page.textContent('.optimized')).toMatch(\n '[success] alias optimized',\n )\n})\n\ntest('aliased module', async () => {\n expect(await page.textContent('.aliased-module')).toMatch(\n '[success] aliased module',\n )\n})\n\ntest('url conflict alias', async () => {\n expect(await page.textContent('.url-conflict')).toMatch(\n '[success] url conflict alias',\n )\n})\n\ntest('custom resolver', async () => {\n expect(await page.textContent('.custom-resolver')).toMatch(\n '[success] alias to custom-resolver path',\n )\n})", "messages": null, "tools": null} {"id": "72514a219793e7c1", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/worker/deeply-nested-second-worker.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 471, "sha256": "e914ccf3ecfae3ebc082ce7860ef94a987e90e6adfbb35885b8db4f02ea76d0d", "text": "self.postMessage({\n type: 'deeplyNestedSecondWorker',\n data: [\n 'Hello from second level nested worker',\n import.meta.env.BASE_URL,\n self.location.url,\n import.meta.url,\n ].join(' '),\n})\n\nconst deeplyNestedThirdWorker = new Worker(\n new URL('deeply-nested-third-worker.js', import.meta.url),\n { type: 'module' },\n)\ndeeplyNestedThirdWorker.addEventListener('message', (ev) => {\n self.postMessage(ev.data)\n})\n\nconsole.log('deeply-nested-second-worker.js')", "messages": null, "tools": null} {"id": "727e724ade41270b", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/includes/glossary.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 1302, "sha256": "27e4c456eb1fc8628350893ff0af583a35483d7eee98d22bccb860de2ba90353", "text": "\n\n*[ADL]: Argument-dependent lookup\n*[API]: Application Programming Interfaces\n*[ASCII]: American Standard Code for Information Interchange\n*[BDFL]: Benevolent Dictator for Life\n*[BJData]: Binary JData\n*[BSON]: Binary JSON\n*[CBOR]: Concise Binary Object Representation\n*[CC0]: Creative Commons Zero\n*[CI]: Continuous Integration\n*[DOM]: Document Object Model\n*[EOF]: End of File\n*[FAQ]: Frequently Asked Questions\n*[GCC]: GNU Compiler Collection\n*[HTTP]: Hypertext Transfer Protocol\n*[ICC]: Intel C++ Compiler\n*[IEEE]: Institute of Electrical and Electronics Engineers\n*[ISO]: International Organization for Standardization\n*[JSON]: JavaScript Object Notation\n*[MIT]: Massachusetts Institute of Technology\n*[MSVC]: Microsoft Visual C++\n*[MsgPack]: MessagePack\n*[NASA]: National Aeronautics and Space Administration\n*[NDK]: Native Development Kit\n*[NaN]: Not a Number\n*[RFC]: Request for Comments\n*[RTTI]: Runtime Type Information\n*[SAX]: Simple API for XML\n*[SDK]: Software Development Kit\n*[SFINAE]: Substitution failure is not an error\n*[SHA]: Secure Hash Algorithm\n*[SPDX]: Software Package Data Exchange\n*[STL]: Standard Template Library\n*[UBJSON]: Universal Binary JSON\n*[UTF]: Unicode Transformation Format", "messages": null, "tools": null} {"id": "72d3e615602b0741", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "include/nlohmann/detail/input/binary_reader.hpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 114512, "sha256": "9f45ae8737c291897a45c2e3dc07157429b25817e2110fee6a7a3d65f6e29b79", "text": "// __ _____ _____ _____\n// __| | __| | | | JSON for Modern C++\n// | | |__ | | | | | | version 3.12.0\n// |_____|_____|_____|_|___| https://github.com/nlohmann/json\n//\n// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann \n// SPDX-License-Identifier: MIT\n\n#pragma once\n\n#include // generate_n\n#include // array\n#include // ldexp\n#include // size_t\n#include // uint8_t, uint16_t, uint32_t, uint64_t, uintmax_t\n#include // snprintf\n#include // memcpy\n#include // back_inserter\n#include // numeric_limits\n#include // char_traits, string\n#include // make_pair, move\n#include // vector\n#ifdef __cpp_lib_byteswap\n #include //byteswap\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nNLOHMANN_JSON_NAMESPACE_BEGIN\nnamespace detail\n{\n\n/// how to treat CBOR tags\nenum class cbor_tag_handler_t\n{\n error, ///< throw a parse_error exception in case of a tag\n ignore, ///< ignore tags\n store ///< store tags as binary type\n};\n\n/*!\n@brief determine system byte order\n\n@return true if and only if system's byte order is little endian\n\n@note from https://stackoverflow.com/a/1001328/266378\n*/\ninline bool little_endianness(int num = 1) noexcept\n{\n return *reinterpret_cast(&num) == 1;\n}\n\n///////////////////\n// binary reader //\n///////////////////\n\n/*!\n@brief deserialization of CBOR, MessagePack, and UBJSON values\n*/\ntemplate>\nclass binary_reader\n{\n using number_integer_t = typename BasicJsonType::number_integer_t;\n using number_unsigned_t = typename BasicJsonType::number_unsigned_t;\n using number_float_t = typename BasicJsonType::number_float_t;\n using string_t = typename BasicJsonType::string_t;\n using binary_t = typename BasicJsonType::binary_t;\n using json_sax_t = SAX;\n using char_type = typename InputAdapterType::char_type;\n using char_int_type = typename char_traits::int_type;\n\n public:\n /*!\n @brief create a binary reader\n\n @param[in] adapter input adapter to read from\n */\n explicit binary_reader(InputAdapterType&& adapter, const input_format_t format = input_format_t::json) noexcept : ia(std::move(adapter)), input_format(format)\n {\n (void)detail::is_sax_static_asserts {};\n }\n\n // make class move-only\n binary_reader(const binary_reader&) = delete;\n binary_reader(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)\n binary_reader& operator=(const binary_reader&) = delete;\n binary_reader& operator=(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)\n ~binary_reader() = default;\n\n /*!\n @param[in] format the binary format to parse\n @param[in] sax_ a SAX event processor\n @param[in] strict whether to expect the input to be consumed completed\n @param[in] tag_handler how to treat CBOR tags\n\n @return whether parsing was successful\n */\n JSON_HEDLEY_NON_NULL(3)\n bool sax_parse(const input_format_t format,\n json_sax_t* sax_,\n const bool strict = true,\n const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error)\n {\n sax = sax_;\n bool result = false;\n\n switch (format)\n {\n case input_format_t::bson:\n result = parse_bson_internal();\n break;\n\n case input_format_t::cbor:\n result = parse_cbor_internal(true, tag_handler);\n break;\n\n case input_format_t::msgpack:\n result = parse_msgpack_internal();\n break;\n\n case input_format_t::ubjson:\n case input_format_t::bjdata:\n result = parse_ubjson_internal();\n break;\n\n case input_format_t::json: // LCOV_EXCL_LINE\n default: // LCOV_EXCL_LINE\n JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE\n }\n\n // strict mode: next byte must be EOF\n if (result && strict)\n {\n if (input_format == input_format_t::ubjson || input_format == input_format_t::bjdata)\n {\n get_ignore_noop();\n }\n else\n {\n get();\n }\n\n if (JSON_HEDLEY_UNLIKELY(current != char_traits::eof()))\n {\n return sax->parse_error(chars_read, get_token_string(), parse_error::create(110, chars_read,\n exception_message(input_format, concat(\"expected end of input; last byte: 0x\", get_token_string()), \"value\"), nullptr));\n }\n }\n\n return result;\n }\n\n private:\n //////////\n // BSON //\n //////////\n\n /*!\n @brief Validate a BSON document's declared size against the bytes read.\n\n A BSON document starts with an int32 that counts its own total length in\n bytes, including that prefix and the trailing 0x00. The reader is driven\n by the terminator rather than the declared length, so without this check a\n nested document could declare a length that disagrees with where its\n terminator actually falls and quietly hand the bytes in between to the\n enclosing document. A well-formed document is at least 5 bytes (the prefix\n plus the terminator); the equality also rejects those impossible sizes,\n since at least 5 bytes are always consumed.\n\n @param[in] document_start value of chars_read before the size prefix\n @param[in] document_size the declared document size\n @return whether the declared size matches the number of bytes read\n */\n bool check_bson_document_size(const std::size_t document_start, const std::int32_t document_size)\n {\n if (JSON_HEDLEY_UNLIKELY(document_size < 0 || static_cast(document_size) != chars_read - document_start))\n {\n return sax->parse_error(chars_read, get_token_string(), parse_error::create(112, chars_read,\n exception_message(input_format_t::bson, concat(\"document size \", std::to_string(document_size), \" does not match the number of bytes read (\", std::to_string(chars_read - document_start), \")\"), \"document\"), nullptr));\n }\n return true;\n }\n\n /*!\n @brief Reads in a BSON-object and passes it to the SAX-parser.\n @return whether a valid BSON-value was passed to the SAX parser\n */\n bool parse_bson_internal()\n {\n const std::size_t document_start = chars_read;\n std::int32_t document_size{};\n if (!get_number(input_format_t::bson, document_size))\n {\n return false;\n }\n\n if (JSON_HEDLEY_UNLIKELY(!sax->start_object(detail::unknown_size())))\n {\n return false;\n }\n\n if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/false)))\n {\n return false;\n }\n\n if (JSON_HEDLEY_UNLIKELY(!check_bson_document_size(document_start, document_size)))\n {\n return false;\n }\n\n return sax->end_object();\n }\n\n /*!\n @brief Parses a C-style string from the BSON input.\n @param[in,out] result A reference to the string variable where the read\n string is to be stored.\n @return `true` if the \\x00-byte indicating the end of the string was\n encountered before the EOF; false` indicates an unexpected EOF.\n */\n bool get_bson_cstr(string_t& result)\n {\n auto out = std::back_inserter(result);\n while (true)\n {\n get();\n if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, \"cstring\")))\n {\n return false;\n }\n if (current == 0x00)\n {\n return true;\n }\n *out++ = static_cast(current);\n }\n }\n\n /*!\n @brief Parses a zero-terminated string of length @a len from the BSON\n input.\n @param[in] len The length (including the zero-byte at the end) of the\n string to be read.\n @param[in,out] result A reference to the string variable where the read\n string is to be stored.\n @tparam NumberType The type of the length @a len\n @pre len >= 1\n @return `true` if the string was successfully parsed\n */\n template\n bool get_bson_string(const NumberType len, string_t& result)\n {\n if (JSON_HEDLEY_UNLIKELY(len < 1))\n {\n auto last_token = get_token_string();\n return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read,\n exception_message(input_format_t::bson, concat(\"string length must be at least 1, is \", std::to_string(len)), \"string\"), nullptr));\n }\n\n return get_string(input_format_t::bson, len - static_cast(1), result) && get() != char_traits::eof();\n }\n\n /*!\n @brief Parses a byte array input of length @a len from the BSON input.\n @param[in] len The length of the byte array to be read.\n @param[in,out] result A reference to the binary variable where the read\n array is to be stored.\n @tparam NumberType The type of the length @a len\n @pre len >= 0\n @return `true` if the byte array was successfully parsed\n */\n template\n bool get_bson_binary(const NumberType len, binary_t& result)\n {\n if (JSON_HEDLEY_UNLIKELY(len < 0))\n {\n auto last_token = get_token_string();\n return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read,\n exception_message(input_format_t::bson, concat(\"byte array length cannot be negative, is \", std::to_string(len)), \"binary\"), nullptr));\n }\n\n // All BSON binary values have a subtype\n std::uint8_t subtype{};\n if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::bson, subtype)))\n {\n return false;\n }\n result.set_subtype(subtype);\n\n return get_binary(input_format_t::bson, len, result);\n }\n\n /*!\n @brief Read a BSON document element of the given @a element_type.\n @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html\n @param[in] element_type_parse_position The position in the input stream,\n where the `element_type` was read.\n @warning Not all BSON element types are supported yet. An unsupported\n @a element_type will give rise to a parse_error.114:\n Unsupported BSON record type 0x...\n @return whether a valid BSON-object/array was passed to the SAX parser\n */\n bool parse_bson_element_internal(const char_int_type element_type,\n const std::size_t element_type_parse_position)\n {\n switch (element_type)\n {\n case 0x01: // double\n {\n double number{};\n return get_number(input_format_t::bson, number) && sax->number_float(static_cast(number), \"\");\n }\n\n case 0x02: // string\n {\n std::int32_t len{};\n string_t value;\n return get_number(input_format_t::bson, len) && get_bson_string(len, value) && sax->string(value);\n }\n\n case 0x03: // object\n {\n return parse_bson_internal();\n }\n\n case 0x04: // array\n {\n return parse_bson_array();\n }\n\n case 0x05: // binary\n {\n std::int32_t len{};\n binary_t value;\n return get_number(input_format_t::bson, len) && get_bson_binary(len, value) && sax->binary(value);\n }\n\n case 0x08: // boolean\n {\n std::uint8_t value{};\n return get_number(input_format_t::bson, value) && sax->boolean(value != 0);\n }\n\n case 0x0A: // null\n {\n return sax->null();\n }\n\n case 0x10: // int32\n {\n std::int32_t value{};\n return get_number(input_format_t::bson, value) && sax->number_integer(value);\n }\n\n case 0x12: // int64\n {\n std::int64_t value{};\n return get_number(input_format_t::bson, value) && sax->number_integer(value);\n }\n\n case 0x11: // uint64\n {\n std::uint64_t value{};\n return get_number(input_format_t::bson, value) && sax->number_unsigned(value);\n }\n\n default: // anything else is not supported (yet)\n {\n std::array cr{{}};\n static_cast((std::snprintf)(cr.data(), cr.size(), \"%.2hhX\", static_cast(element_type))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)\n const std::string cr_str{cr.data()};\n return sax->parse_error(element_type_parse_position, cr_str,\n parse_error::create(114, element_type_parse_position, concat(\"Unsupported BSON record type 0x\", cr_str), nullptr));\n }\n }\n }\n\n /*!\n @brief Read a BSON element list (as specified in the BSON-spec)\n\n The same binary layout is used for objects and arrays, hence it must be\n indicated with the argument @a is_array which one is expected\n (true --> array, false --> object).\n\n @param[in] is_array Determines if the element list being read is to be\n treated as an object (@a is_array == false), or as an\n array (@a is_array == true).\n @return whether a valid BSON-object/array was passed to the SAX parser\n */\n bool parse_bson_element_list(const bool is_array)\n {\n string_t key;\n\n while (auto element_type = get())\n {\n if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, \"element list\")))\n {\n return false;\n }\n\n const std::size_t element_type_parse_position = chars_read;\n if (JSON_HEDLEY_UNLIKELY(!get_bson_cstr(key)))\n {\n return false;\n }\n\n if (!is_array && !sax->key(key))\n {\n return false;\n }\n\n if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_internal(element_type, element_type_parse_position)))\n {\n return false;\n }\n\n // get_bson_cstr only appends\n key.clear();\n }\n\n return true;\n }\n\n /*!\n @brief Reads an array from the BSON input and passes it to the SAX-parser.\n @return whether a valid BSON-array was passed to the SAX parser\n */\n bool parse_bson_array()\n {\n const std::size_t document_start = chars_read;\n std::int32_t document_size{};\n if (!get_number(input_format_t::bson, document_size))\n {\n return false;\n }\n\n if (JSON_HEDLEY_UNLIKELY(!sax->start_array(detail::unknown_size())))\n {\n return false;\n }\n\n if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/true)))\n {\n return false;\n }\n\n if (JSON_HEDLEY_UNLIKELY(!check_bson_document_size(document_start, document_size)))\n {\n return false;\n }\n\n return sax->end_array();\n }\n\n //////////\n // CBOR //\n //////////\n\n template\n bool get_cbor_negative_integer()\n {\n NumberType number{};\n if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::cbor, number)))\n {\n return false;\n }\n const auto max_val = static_cast((std::numeric_limits::max)());\n if (number > max_val)\n {\n return sax->parse_error(chars_read, get_token_string(),\n parse_error::create(112, chars_read,\n exception_message(input_format_t::cbor, \"negative integer overflow\", \"value\"), nullptr));\n }\n return sax->number_integer(static_cast(-1) - static_cast(number));\n }\n\n /*!\n @param[in] get_char whether a new character should be retrieved from the\n input (true) or whether the last read character should\n be considered instead (false)\n @param[in] tag_handler how CBOR tags should be treated\n\n @return whether a valid CBOR value was passed to the SAX parser\n */\n bool parse_cbor_internal(const bool get_char,\n const cbor_tag_handler_t tag_handler)\n {\n switch (get_char ? get() : current)\n {\n // EOF\n case char_traits::eof():\n return unexpect_eof(input_format_t::cbor, \"value\");\n\n // Integer 0x00..0x17 (0..23)\n case 0x00:\n case 0x01:\n case 0x02:\n case 0x03:\n case 0x04:\n case 0x05:\n case 0x06:\n case 0x07:\n case 0x08:\n case 0x09:\n case 0x0A:\n case 0x0B:\n case 0x0C:\n case 0x0D:\n case 0x0E:\n case 0x0F:\n case 0x10:\n case 0x11:\n case 0x12:\n case 0x13:\n case 0x14:\n case 0x15:\n case 0x16:\n case 0x17:\n return sax->number_unsigned(static_cast(current));\n\n case 0x18: // Unsigned integer (one-byte uint8_t follows)\n {\n std::uint8_t number{};\n return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);\n }\n\n case 0x19: // Unsigned integer (two-byte uint16_t follows)\n {\n std::uint16_t number{};\n return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);\n }\n\n case 0x1A: // Unsigned integer (four-byte uint32_t follows)\n {\n std::uint32_t number{};\n return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);\n }\n\n case 0x1B: // Unsigned integer (eight-byte uint64_t follows)\n {\n std::uint64_t number{};\n return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);\n }\n\n // Negative integer -1-0x00..-1-0x17 (-1..-24)\n case 0x20:\n case 0x21:\n case 0x22:\n case 0x23:\n case 0x24:\n case 0x25:\n case 0x26:\n case 0x27:\n case 0x28:\n case 0x29:\n case 0x2A:\n case 0x2B:\n case 0x2C:\n case 0x2D:\n case 0x2E:\n case 0x2F:\n case 0x30:\n case 0x31:\n case 0x32:\n case 0x33:\n case 0x34:\n case 0x35:\n case 0x36:\n case 0x37:\n return sax->number_integer(static_cast(0x20 - 1 - current));\n\n case 0x38: // Negative integer (one-byte uint8_t follows)\n return get_cbor_negative_integer();\n\n case 0x39: // Negative integer -1-n (two-byte uint16_t follows)\n return get_cbor_negative_integer();\n\n case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)\n return get_cbor_negative_integer();\n\n case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)\n return get_cbor_negative_integer();\n\n // Binary data (0x00..0x17 bytes follow)\n case 0x40:\n case 0x41:\n case 0x42:\n case 0x43:\n case 0x44:\n case 0x45:\n case 0x46:\n case 0x47:\n case 0x48:\n case 0x49:\n case 0x4A:\n case 0x4B:\n case 0x4C:\n case 0x4D:\n case 0x4E:\n case 0x4F:\n case 0x50:\n case 0x51:\n case 0x52:\n case 0x53:\n case 0x54:\n case 0x55:\n case 0x56:\n case 0x57:\n case 0x58: // Binary data (one-byte uint8_t for n follows)\n case 0x59: // Binary data (two-byte uint16_t for n follow)\n case 0x5A: // Binary data (four-byte uint32_t for n follow)\n case 0x5B: // Binary data (eight-byte uint64_t for n follow)\n case 0x5F: // Binary data (indefinite length)\n {\n binary_t b;\n return get_cbor_binary(b) && sax->binary(b);\n }\n\n // UTF-8 string (0x00..0x17 bytes follow)\n case 0x60:\n case 0x61:\n case 0x62:\n case 0x63:\n case 0x64:\n case 0x65:\n case 0x66:\n case 0x67:\n case 0x68:\n case 0x69:\n case 0x6A:\n case 0x6B:\n case 0x6C:\n case 0x6D:\n case 0x6E:\n case 0x6F:\n case 0x70:\n case 0x71:\n case 0x72:\n case 0x73:\n case 0x74:\n case 0x75:\n case 0x76:\n case 0x77:\n case 0x78: // UTF-8 string (one-byte uint8_t for n follows)\n case 0x79: // UTF-8 string (two-byte uint16_t for n follow)\n case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)\n case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)\n case 0x7F: // UTF-8 string (indefinite length)\n {\n string_t s;\n return get_cbor_string(s) && sax->string(s);\n }\n\n // array (0x00..0x17 data items follow)\n case 0x80:\n case 0x81:\n case 0x82:\n case 0x83:\n case 0x84:\n case 0x85:\n case 0x86:\n case 0x87:\n case 0x88:\n case 0x89:\n case 0x8A:\n case 0x8B:\n case 0x8C:\n case 0x8D:\n case 0x8E:\n case 0x8F:\n case 0x90:\n case 0x91:\n case 0x92:\n case 0x93:\n case 0x94:\n case 0x95:\n case 0x96:\n case 0x97:\n return get_cbor_array(\n conditional_static_cast(static_cast(current) & 0x1Fu), tag_handler);\n\n case 0x98: // array (one-byte uint8_t for n follows)\n {\n std::uint8_t len{};\n return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler);\n }\n\n case 0x99: // array (two-byte uint16_t for n follow)\n {\n std::uint16_t len{};\n return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler);\n }\n\n case 0x9A: // array (four-byte uint32_t for n follow)\n {\n std::uint32_t len{};\n std::size_t size{};\n return get_number(input_format_t::cbor, len) && get_cbor_container_size(len, size, \"array\") && get_cbor_array(size, tag_handler);\n }\n\n case 0x9B: // array (eight-byte uint64_t for n follow)\n {\n std::uint64_t len{};\n std::size_t size{};\n return get_number(input_format_t::cbor, len) && get_cbor_container_size(len, size, \"array\") && get_cbor_array(size, tag_handler);\n }\n\n case 0x9F: // array (indefinite length)\n return get_cbor_array(detail::unknown_size(), tag_handler);\n\n // map (0x00..0x17 pairs of data items follow)\n case 0xA0:\n case 0xA1:\n case 0xA2:\n case 0xA3:\n case 0xA4:\n case 0xA5:\n case 0xA6:\n case 0xA7:\n case 0xA8:\n case 0xA9:\n case 0xAA:\n case 0xAB:\n case 0xAC:\n case 0xAD:\n case 0xAE:\n case 0xAF:\n case 0xB0:\n case 0xB1:\n case 0xB2:\n case 0xB3:\n case 0xB4:\n case 0xB5:\n case 0xB6:\n case 0xB7:\n return get_cbor_object(conditional_static_cast(static_cast(current) & 0x1Fu), tag_handler);\n\n case 0xB8: // map (one-byte uint8_t for n follows)\n {\n std::uint8_t len{};\n return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler);\n }\n\n case 0xB9: // map (two-byte uint16_t for n follow)\n {\n std::uint16_t len{};\n return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler);\n }\n\n case 0xBA: // map (four-byte uint32_t for n follow)\n {\n std::uint32_t len{};\n std::size_t size{};\n return get_number(input_format_t::cbor, len) && get_cbor_container_size(len, size, \"map\") && get_cbor_object(size, tag_handler);\n }\n\n case 0xBB: // map (eight-byte uint64_t for n follow)\n {\n std::uint64_t len{};\n std::size_t size{};\n return get_number(input_format_t::cbor, len) && get_cbor_container_size(len, size, \"map\") && get_cbor_object(size, tag_handler);\n }\n\n case 0xBF: // map (indefinite length)\n return get_cbor_object(detail::unknown_size(), tag_handler);\n\n case 0xC6: // tagged item\n case 0xC7:\n case 0xC8:\n case 0xC9:\n case 0xCA:\n case 0xCB:\n case 0xCC:\n case 0xCD:\n case 0xCE:\n case 0xCF:\n case 0xD0:\n case 0xD1:\n case 0xD2:\n case 0xD3:\n case 0xD4:\n case 0xD8: // tagged item (1 byte follows)\n case 0xD9: // tagged item (2 bytes follow)\n case 0xDA: // tagged item (4 bytes follow)\n case 0xDB: // tagged item (8 bytes follow)\n {\n switch (tag_handler)\n {\n case cbor_tag_handler_t::error:\n {\n auto last_token = get_token_string();\n return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read,\n exception_message(input_format_t::cbor, concat(\"invalid byte: 0x\", last_token), \"value\"), nullptr));\n }\n\n case cbor_tag_handler_t::ignore:\n {\n // ignore binary subtype\n switch (current)\n {\n case 0xD8:\n {\n std::uint8_t subtype_to_ignore{};\n if (!get_number(input_format_t::cbor, subtype_to_ignore))\n {\n return false;\n }\n break;\n }\n case 0xD9:\n {\n std::uint16_t subtype_to_ignore{};\n if (!get_number(input_format_t::cbor, subtype_to_ignore))\n {\n return false;\n }\n break;\n }\n case 0xDA:\n {\n std::uint32_t subtype_to_ignore{};\n if (!get_number(input_format_t::cbor, subtype_to_ignore))\n {\n return false;\n }\n break;\n }\n case 0xDB:\n {\n std::uint64_t subtype_to_ignore{};\n if (!get_number(input_format_t::cbor, subtype_to_ignore))\n {\n return false;\n }\n break;\n }\n default:\n break;\n }\n return parse_cbor_internal(true, tag_handler);\n }\n\n case cbor_tag_handler_t::store:\n {\n binary_t b;\n // use binary subtype and store in a binary container\n switch (current)\n {\n case 0xD8:\n {\n std::uint8_t subtype{};\n if (!get_number(input_format_t::cbor, subtype))\n {\n return false;\n }\n b.set_subtype(detail::conditional_static_cast(subtype));\n break;\n }\n case 0xD9:\n {\n std::uint16_t subtype{};\n if (!get_number(input_format_t::cbor, subtype))\n {\n return false;\n }\n b.set_subtype(detail::conditional_static_cast(subtype));\n break;\n }\n case 0xDA:\n {\n std::uint32_t subtype{};\n if (!get_number(input_format_t::cbor, subtype))\n {\n return false;\n }\n b.set_subtype(detail::conditional_static_cast(subtype));\n break;\n }\n case 0xDB:\n {\n std::uint64_t subtype{};\n if (!get_number(input_format_t::cbor, subtype))\n {\n return false;\n }\n b.set_subtype(detail::conditional_static_cast(subtype));\n break;\n }\n default:\n return parse_cbor_internal(true, tag_handler);\n }\n get();\n return get_cbor_binary(b) && sax->binary(b);\n }\n\n default: // LCOV_EXCL_LINE\n JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE\n return false; // LCOV_EXCL_LINE\n }\n }\n\n case 0xF4: // false\n return sax->boolean(false);\n\n case 0xF5: // true\n return sax->boolean(true);\n\n case 0xF6: // null\n return sax->null();\n\n case 0xF9: // Half-Precision Float (two-byte IEEE 754)\n {\n const auto byte1_raw = get();\n if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, \"number\")))\n {\n return false;\n }\n const auto byte2_raw = get();\n if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, \"number\")))\n {\n return false;\n }\n\n const auto byte1 = static_cast(byte1_raw);\n const auto byte2 = static_cast(byte2_raw);\n\n // Code from RFC 8949, Appendix D, Figure 3:\n // As half-precision floating-point numbers were only added\n // to IEEE 754 in 2008, today's programming platforms often\n // still only have limited support for them. It is very\n // easy to include at least decoding support for them even\n // without such support. An example of a small decoder for\n // half-precision floating-point numbers in the C language\n // is shown in Fig. 3.\n const auto half = static_cast((byte1 << 8u) + byte2);\n const double val = [&half]\n {\n const int exp = (half >> 10u) & 0x1Fu;\n const unsigned int mant = half & 0x3FFu;\n JSON_ASSERT(exp <= 31);\n JSON_ASSERT(mant <= 1023);\n switch (exp)\n {\n case 0:\n return std::ldexp(mant, -24);\n case 31:\n return (mant == 0)\n ? std::numeric_limits::infinity()\n : std::numeric_limits::quiet_NaN();\n default:\n return std::ldexp(mant + 1024, exp - 25);\n }\n }();\n return sax->number_float((half & 0x8000u) != 0\n ? static_cast(-val)\n : static_cast(val), \"\");\n }\n\n case 0xFA: // Single-Precision Float (four-byte IEEE 754)\n {\n float number{};\n return get_number(input_format_t::cbor, number) && sax->number_float(static_cast(number), \"\");\n }\n\n case 0xFB: // Double-Precision Float (eight-byte IEEE 754)\n {\n double number{};\n return get_number(input_format_t::cbor, number) && sax->number_float(static_cast(number), \"\");\n }\n\n default: // anything else (0xFF is handled inside the other types)\n {\n auto last_token = get_token_string();\n return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read,\n exception_message(input_format_t::cbor, concat(\"invalid byte: 0x\", last_token), \"value\"), nullptr));\n }\n }\n }\n\n /*!\n @brief reads a CBOR string\n\n This function first reads starting bytes to determine the expected\n string length and then copies this number of bytes into a string.\n Additionally, CBOR's strings with indefinite lengths are supported.\n\n @param[out] result created string\n\n @return whether string creation completed\n */\n bool get_cbor_string(string_t& result)\n {\n if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, \"string\")))\n {\n return false;\n }\n\n switch (current)\n {\n // UTF-8 string (0x00..0x17 bytes follow)\n case 0x60:\n case 0x61:\n case 0x62:\n case 0x63:\n case 0x64:\n case 0x65:\n case 0x66:\n case 0x67:\n case 0x68:\n case 0x69:\n case 0x6A:\n case 0x6B:\n case 0x6C:\n case 0x6D:\n case 0x6E:\n case 0x6F:\n case 0x70:\n case 0x71:\n case 0x72:\n case 0x73:\n case 0x74:\n case 0x75:\n case 0x76:\n case 0x77:\n {\n return get_string(input_format_t::cbor, static_cast(current) & 0x1Fu, result);\n }\n\n case 0x78: // UTF-8 string (one-byte uint8_t for n follows)\n {\n std::uint8_t len{};\n return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);\n }\n\n case 0x79: // UTF-8 string (two-byte uint16_t for n follow)\n {\n std::uint16_t len{};\n return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);\n }\n\n case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)\n {\n std::uint32_t len{};\n return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);\n }\n\n case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)\n {\n std::uint64_t len{};\n return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);\n }\n\n case 0x7F: // UTF-8 string (indefinite length)\n {\n while (get() != 0xFF)\n {\n string_t chunk;\n if (!get_cbor_string(chunk))\n {\n return false;\n }\n result.append(chunk);\n }\n return true;\n }\n\n default:\n {\n auto last_token = get_token_string();\n return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read,\n exception_message(input_format_t::cbor, concat(\"expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0x\", last_token), \"string\"), nullptr));\n }\n }\n }\n\n /*!\n @brief reads a CBOR byte array\n\n This function first reads starting bytes to determine the expected\n byte array length and then copies this number of bytes into the byte array.\n Additionally, CBOR's byte arrays with indefinite lengths are supported.\n\n @param[out] result created byte array\n\n @return whether byte array creation completed\n */\n bool get_cbor_binary(binary_t& result)\n {\n if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, \"binary\")))\n {\n return false;\n }\n\n switch (current)\n {\n // Binary data (0x00..0x17 bytes follow)\n case 0x40:\n case 0x41:\n case 0x42:\n case 0x43:\n case 0x44:\n case 0x45:\n case 0x46:\n case 0x47:\n case 0x48:\n case 0x49:\n case 0x4A:\n case 0x4B:\n case 0x4C:\n case 0x4D:\n case 0x4E:\n case 0x4F:\n case 0x50:\n case 0x51:\n case 0x52:\n case 0x53:\n case 0x54:\n case 0x55:\n case 0x56:\n case 0x57:\n {\n return get_binary(input_format_t::cbor, static_cast(current) & 0x1Fu, result);\n }\n\n case 0x58: // Binary data (one-byte uint8_t for n follows)\n {\n std::uint8_t len{};\n return get_number(input_format_t::cbor, len) &&\n get_binary(input_format_t::cbor, len, result);\n }\n\n case 0x59: // Binary data (two-byte uint16_t for n follow)\n {\n std::uint16_t len{};\n return get_number(input_format_t::cbor, len) &&\n get_binary(input_format_t::cbor, len, result);\n }\n\n case 0x5A: // Binary data (four-byte uint32_t for n follow)\n {\n std::uint32_t len{};\n return get_number(input_format_t::cbor, len) &&\n get_binary(input_format_t::cbor, len, result);\n }\n\n case 0x5B: // Binary data (eight-byte uint64_t for n follow)\n {\n std::uint64_t len{};\n return get_number(input_format_t::cbor, len) &&\n get_binary(input_format_t::cbor, len, result);\n }\n\n case 0x5F: // Binary data (indefinite length)\n {\n while (get() != 0xFF)\n {\n binary_t chunk;\n if (!get_cbor_binary(chunk))\n {\n return false;\n }\n result.insert(result.end(), chunk.begin(), chunk.end());\n }\n return true;\n }\n\n default:\n {\n auto last_token = get_token_string();\n return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read,\n exception_message(input_format_t::cbor, concat(\"expected length specification (0x40-0x5B) or indefinite binary array type (0x5F); last byte: 0x\", last_token), \"binary\"), nullptr));\n }\n }\n }\n\n /*!\n @brief narrow a definite CBOR array/map length to std::size_t\n\n A definite length is rejected if it does not fit in std::size_t or if it\n equals detail::unknown_size(), which is reserved to mark an indefinite-\n length container and would otherwise make the length read as indefinite.\n Both cases exceed any container's max_size(), so no representable input\n is affected.\n\n @param[in] len the declared length\n @param[out] result the length narrowed to std::size_t\n @param[in] context \"array\" or \"map\", for the error message\n @return whether the length is usable\n */\n bool get_cbor_container_size(const std::uint64_t len, std::size_t& result, const char* context)\n {\n if (JSON_HEDLEY_UNLIKELY(!value_in_range_of(len) || len == detail::unknown_size()))\n {\n return sax->parse_error(chars_read, get_token_string(), out_of_range::create(408,\n exception_message(input_format_t::cbor, concat(\"excessive \", context, \" size\"), \"size\"), nullptr));\n }\n result = conditional_static_cast(len);\n return true;\n }\n\n /*!\n @param[in] len the length of the array or detail::unknown_size() for an\n array of indefinite size\n @param[in] tag_handler how CBOR tags should be treated\n @return whether array creation completed\n */\n bool get_cbor_array(const std::size_t len,\n const cbor_tag_handler_t tag_handler)\n {\n if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len)))\n {\n return false;\n }\n\n if (len != detail::unknown_size())\n {\n for (std::size_t i = 0; i < len; ++i)\n {\n if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler)))\n {\n return false;\n }\n }\n }\n else\n {\n while (get() != 0xFF)\n {\n if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(false, tag_handler)))\n {\n return false;\n }\n }\n }\n\n return sax->end_array();\n }\n\n /*!\n @param[in] len the length of the object or detail::unknown_size() for an\n object of indefinite size\n @param[in] tag_handler how CBOR tags should be treated\n @return whether object creation completed\n */\n bool get_cbor_object(const std::size_t len,\n const cbor_tag_handler_t tag_handler)\n {\n if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len)))\n {\n return false;\n }\n\n if (len != 0)\n {\n string_t key;\n if (len != detail::unknown_size())\n {\n for (std::size_t i = 0; i < len; ++i)\n {\n get();\n if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key)))\n {\n return false;\n }\n\n if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler)))\n {\n return false;\n }\n key.clear();\n }\n }\n else\n {\n while (get() != 0xFF)\n {\n if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key)))\n {\n return false;\n }\n\n if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler)))\n {\n return false;\n }\n key.clear();\n }\n }\n }\n\n return sax->end_object();\n }\n\n /////////////\n // MsgPack //\n /////////////\n\n /*!\n @return whether a valid MessagePack value was passed to the SAX parser\n */\n bool parse_msgpack_internal()\n {\n switch (get())\n {\n // EOF\n case char_traits::eof():\n return unexpect_eof(input_format_t::msgpack, \"value\");\n\n // positive fixint\n case 0x00:\n case 0x01:\n case 0x02:\n case 0x03:\n case 0x04:\n case 0x05:\n case 0x06:\n case 0x07:\n case 0x08:\n case 0x09:\n case 0x0A:\n case 0x0B:\n case 0x0C:\n case 0x0D:\n case 0x0E:\n case 0x0F:\n case 0x10:\n case 0x11:\n case 0x12:\n case 0x13:\n case 0x14:\n case 0x15:\n case 0x16:\n case 0x17:\n case 0x18:\n case 0x19:\n case 0x1A:\n case 0x1B:\n case 0x1C:\n case 0x1D:\n case 0x1E:\n case 0x1F:\n case 0x20:\n case 0x21:\n case 0x22:\n case 0x23:\n case 0x24:\n case 0x25:\n case 0x26:\n case 0x27:\n case 0x28:\n case 0x29:\n case 0x2A:\n case 0x2B:\n case 0x2C:\n case 0x2D:\n case 0x2E:\n case 0x2F:\n case 0x30:\n case 0x31:\n case 0x32:\n case 0x33:\n case 0x34:\n case 0x35:\n case 0x36:\n case 0x37:\n case 0x38:\n case 0x39:\n case 0x3A:\n case 0x3B:\n case 0x3C:\n case 0x3D:\n case 0x3E:\n case 0x3F:\n case 0x40:\n case 0x41:\n case 0x42:\n case 0x43:\n case 0x44:\n case 0x45:\n case 0x46:\n case 0x47:\n case 0x48:\n case 0x49:\n case 0x4A:\n case 0x4B:\n case 0x4C:\n case 0x4D:\n case 0x4E:\n case 0x4F:\n case 0x50:\n case 0x51:\n case 0x52:\n case 0x53:\n case 0x54:\n case 0x55:\n case 0x56:\n case 0x57:\n case 0x58:\n case 0x59:\n case 0x5A:\n case 0x5B:\n case 0x5C:\n case 0x5D:\n case 0x5E:\n case 0x5F:\n case 0x60:\n case 0x61:\n case 0x62:\n case 0x63:\n case 0x64:\n case 0x65:\n case 0x66:\n case 0x67:\n case 0x68:\n case 0x69:\n case 0x6A:\n case 0x6B:\n case 0x6C:\n case 0x6D:\n case 0x6E:\n case 0x6F:\n case 0x70:\n case 0x71:\n case 0x72:\n case 0x73:\n case 0x74:\n case 0x75:\n case 0x76:\n case 0x77:\n case 0x78:\n case 0x79:\n case 0x7A:\n case 0x7B:\n case 0x7C:\n case 0x7D:\n case 0x7E:\n case 0x7F:\n return sax->number_unsigned(static_cast(current));\n\n // fixmap\n case 0x80:\n case 0x81:\n case 0x82:\n case 0x83:\n case 0x84:\n case 0x85:\n case 0x86:\n case 0x87:\n case 0x88:\n case 0x89:\n case 0x8A:\n case 0x8B:\n case 0x8C:\n case 0x8D:\n case 0x8E:\n case 0x8F:\n return get_msgpack_object(conditional_static_cast(static_cast(current) & 0x0Fu));\n\n // fixarray\n case 0x90:\n case 0x91:\n case 0x92:\n case 0x93:\n case 0x94:\n case 0x95:\n case 0x96:\n case 0x97:\n case 0x98:\n case 0x99:\n case 0x9A:\n case 0x9B:\n case 0x9C:\n case 0x9D:\n case 0x9E:\n case 0x9F:\n return get_msgpack_array(conditional_static_cast(static_cast(current) & 0x0Fu));\n\n // fixstr\n case 0xA0:\n case 0xA1:\n case 0xA2:\n case 0xA3:\n case 0xA4:\n case 0xA5:\n case 0xA6:\n case 0xA7:\n case 0xA8:\n case 0xA9:\n case 0xAA:\n case 0xAB:\n case 0xAC:\n case 0xAD:\n case 0xAE:\n case 0xAF:\n case 0xB0:\n case 0xB1:\n case 0xB2:\n case 0xB3:\n case 0xB4:\n case 0xB5:\n case 0xB6:\n case 0xB7:\n case 0xB8:\n case 0xB9:\n case 0xBA:\n case 0xBB:\n case 0xBC:\n case 0xBD:\n case 0xBE:\n case 0xBF:\n case 0xD9: // str 8\n case 0xDA: // str 16\n case 0xDB: // str 32\n {\n string_t s;\n return get_msgpack_string(s) && sax->string(s);\n }\n\n case 0xC0: // nil\n return sax->null();\n\n case 0xC2: // false\n return sax->boolean(false);\n\n case 0xC3: // true\n return sax->boolean(true);\n\n case 0xC4: // bin 8\n case 0xC5: // bin 16\n case 0xC6: // bin 32\n case 0xC7: // ext 8\n case 0xC8: // ext 16\n case 0xC9: // ext 32\n case 0xD4: // fixext 1\n case 0xD5: // fixext 2\n case 0xD6: // fixext 4\n case 0xD7: // fixext 8\n case 0xD8: // fixext 16\n {\n binary_t b;\n return get_msgpack_binary(b) && sax->binary(b);\n }\n\n case 0xCA: // float 32\n {\n float number{};\n return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast(number), \"\");\n }\n\n case 0xCB: // float 64\n {\n double number{};\n return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast(number), \"\");\n }\n\n case 0xCC: // uint 8\n {\n std::uint8_t number{};\n return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);\n }\n\n case 0xCD: // uint 16\n {\n std::uint16_t number{};\n return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);\n }\n\n case 0xCE: // uint 32\n {\n std::uint32_t number{};\n return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);\n }\n\n case 0xCF: // uint 64\n {\n std::uint64_t number{};\n return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);\n }\n\n case 0xD0: // int 8\n {\n std::int8_t number{};\n return get_number(input_format_t::msgpack, number) && sax->number_integer(number);\n }\n\n case 0xD1: // int 16\n {\n std::int16_t number{};\n return get_number(input_format_t::msgpack, number) && sax->number_integer(number);\n }\n\n case 0xD2: // int 32\n {\n std::int32_t number{};\n return get_number(input_format_t::msgpack, number) && sax->number_integer(number);\n }\n\n case 0xD3: // int 64\n {\n std::int64_t number{};\n return get_number(input_format_t::msgpack, number) && sax->number_integer(number);\n }\n\n case 0xDC: // array 16\n {\n std::uint16_t len{};\n return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast(len));\n }\n\n case 0xDD: // array 32\n {\n std::uint32_t len{};\n return get_number(input_format_t::msgpack, len) && get_msgpack_array(conditional_static_cast(len));\n }\n\n case 0xDE: // map 16\n {\n std::uint16_t len{};\n return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast(len));\n }\n\n case 0xDF: // map 32\n {\n std::uint32_t len{};\n return get_number(input_format_t::msgpack, len) && get_msgpack_object(conditional_static_cast(len));\n }\n\n // negative fixint\n case 0xE0:\n case 0xE1:\n case 0xE2:\n case 0xE3:\n case 0xE4:\n case 0xE5:\n case 0xE6:\n case 0xE7:\n case 0xE8:\n case 0xE9:\n case 0xEA:\n case 0xEB:\n case 0xEC:\n case 0xED:\n case 0xEE:\n case 0xEF:\n case 0xF0:\n case 0xF1:\n case 0xF2:\n case 0xF3:\n case 0xF4:\n case 0xF5:\n case 0xF6:\n case 0xF7:\n case 0xF8:\n case 0xF9:\n case 0xFA:\n case 0xFB:\n case 0xFC:\n case 0xFD:\n case 0xFE:\n case 0xFF:\n return sax->number_integer(static_cast(current));\n\n default: // anything else\n {\n auto last_token = get_token_string();\n return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read,\n exception_message(input_format_t::msgpack, concat(\"invalid byte: 0x\", last_token), \"value\"), nullptr));\n }\n }\n }\n\n /*!\n @brief reads a MessagePack string\n\n This function first reads starting bytes to determine the expected\n string length and then copies this number of bytes into a string.\n\n @param[out] result created string\n\n @return whether string creation completed\n */\n bool get_msgpack_string(string_t& result)\n {\n if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::msgpack, \"string\")))\n {\n return false;\n }\n\n switch (current)\n {\n // fixstr\n case 0xA0:\n case 0xA1:\n case 0xA2:\n case 0xA3:\n case 0xA4:\n case 0xA5:\n case 0xA6:\n case 0xA7:\n case 0xA8:\n case 0xA9:\n case 0xAA:\n case 0xAB:\n case 0xAC:\n case 0xAD:\n case 0xAE:\n case 0xAF:\n case 0xB0:\n case 0xB1:\n case 0xB2:\n case 0xB3:\n case 0xB4:\n case 0xB5:\n case 0xB6:\n case 0xB7:\n case 0xB8:\n case 0xB9:\n case 0xBA:\n case 0xBB:\n case 0xBC:\n case 0xBD:\n case 0xBE:\n case 0xBF:\n {\n return get_string(input_format_t::msgpack, static_cast(current) & 0x1Fu, result);\n }\n\n case 0xD9: // str 8\n {\n std::uint8_t len{};\n return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);\n }\n\n case 0xDA: // str 16\n {\n std::uint16_t len{};\n return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);\n }\n\n case 0xDB: // str 32\n {\n std::uint32_t len{};\n return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);\n }\n\n default:\n {\n auto last_token = get_token_string();\n return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read,\n exception_message(input_format_t::msgpack, concat(\"expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0x\", last_token), \"string\"), nullptr));\n }\n }\n }\n\n /*!\n @brief reads a MessagePack byte array\n\n This function first reads starting bytes to determine the expected\n byte array length and then copies this number of bytes into a byte array.\n\n @param[out] result created byte array\n\n @return whether byte array creation completed\n */\n bool get_msgpack_binary(binary_t& result)\n {\n // helper function to set the subtype\n auto assign_and_return_true = [&result](std::int8_t subtype)\n {\n result.set_subtype(static_cast(subtype));\n return true;\n };\n\n switch (current)\n {\n case 0xC4: // bin 8\n {\n std::uint8_t len{};\n return get_number(input_format_t::msgpack, len) &&\n get_binary(input_format_t::msgpack, len, result);\n }\n\n case 0xC5: // bin 16\n {\n std::uint16_t len{};\n return get_number(input_format_t::msgpack, len) &&\n get_binary(input_format_t::msgpack, len, result);\n }\n\n case 0xC6: // bin 32\n {\n std::uint32_t len{};\n return get_number(input_format_t::msgpack, len) &&\n get_binary(input_format_t::msgpack, len, result);\n }\n\n case 0xC7: // ext 8\n {\n std::uint8_t len{};\n std::int8_t subtype{};\n return get_number(input_format_t::msgpack, len) &&\n get_number(input_format_t::msgpack, subtype) &&\n get_binary(input_format_t::msgpack, len, result) &&\n assign_and_return_true(subtype);\n }\n\n case 0xC8: // ext 16\n {\n std::uint16_t len{};\n std::int8_t subtype{};\n return get_number(input_format_t::msgpack, len) &&\n get_number(input_format_t::msgpack, subtype) &&\n get_binary(input_format_t::msgpack, len, result) &&\n assign_and_return_true(subtype);\n }\n\n case 0xC9: // ext 32\n {\n std::uint32_t len{};\n std::int8_t subtype{};\n return get_number(input_format_t::msgpack, len) &&\n get_number(input_format_t::msgpack, subtype) &&\n get_binary(input_format_t::msgpack, len, result) &&\n assign_and_return_true(subtype);\n }\n\n case 0xD4: // fixext 1\n {\n std::int8_t subtype{};\n return get_number(input_format_t::msgpack, subtype) &&\n get_binary(input_format_t::msgpack, 1, result) &&\n assign_and_return_true(subtype);\n }\n\n case 0xD5: // fixext 2\n {\n std::int8_t subtype{};\n return get_number(input_format_t::msgpack, subtype) &&\n get_binary(input_format_t::msgpack, 2, result) &&\n assign_and_return_true(subtype);\n }\n\n case 0xD6: // fixext 4\n {\n std::int8_t subtype{};\n return get_number(input_format_t::msgpack, subtype) &&\n get_binary(input_format_t::msgpack, 4, result) &&\n assign_and_return_true(subtype);\n }\n\n case 0xD7: // fixext 8\n {\n std::int8_t subtype{};\n return get_number(input_format_t::msgpack, subtype) &&\n get_binary(input_format_t::msgpack, 8, result) &&\n assign_and_return_true(subtype);\n }\n\n case 0xD8: // fixext 16\n {\n std::int8_t subtype{};\n return get_number(input_format_t::msgpack, subtype) &&\n get_binary(input_format_t::msgpack, 16, result) &&\n assign_and_return_true(subtype);\n }\n\n default: // LCOV_EXCL_LINE\n return false; // LCOV_EXCL_LINE\n }\n }\n\n /*!\n @param[in] len the length of the array\n @return whether array creation completed\n */\n bool get_msgpack_array(const std::size_t len)\n {\n if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len)))\n {\n return false;\n }\n\n for (std::size_t i = 0; i < len; ++i)\n {\n if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal()))\n {\n return false;\n }\n }\n\n return sax->end_array();\n }\n\n /*!\n @param[in] len the length of the object\n @return whether object creation completed\n */\n bool get_msgpack_object(const std::size_t len)\n {\n if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len)))\n {\n return false;\n }\n\n string_t key;\n for (std::size_t i = 0; i < len; ++i)\n {\n get();\n if (JSON_HEDLEY_UNLIKELY(!get_msgpack_string(key) || !sax->key(key)))\n {\n return false;\n }\n\n if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal()))\n {\n return false;\n }\n key.clear();\n }\n\n return sax->end_object();\n }\n\n ////////////\n // UBJSON //\n ////////////\n\n /*!\n @param[in] get_char whether a new character should be retrieved from the\n input (true, default) or whether the last read\n character should be considered instead\n\n @return whether a valid UBJSON value was passed to the SAX parser\n */\n bool parse_ubjson_internal(const bool get_char = true)\n {\n return get_ubjson_value(get_char ? get_ignore_noop() : current);\n }\n\n /*!\n @brief reject a negative UBJSON/BJData string length\n\n String and key lengths are written with signed integer markers (i, I, l,\n L). A negative value is malformed; without this check get_string() would\n silently treat it as an empty string and leave the following bytes to be\n misread as the next value. This mirrors the non-negative check the\n optimized-container count path already performs in get_ubjson_size_value.\n\n @param[in] len the string length read from the input\n @return whether the length is valid (non-negative)\n */\n template\n bool check_ubjson_string_length(const NumberType len)\n {\n if (JSON_HEDLEY_UNLIKELY(len < 0))\n {\n return sax->parse_error(chars_read, get_token_string(), parse_error::create(113, chars_read,\n exception_message(input_format, \"string length must not be negative\", \"string\"), nullptr));\n }\n return true;\n }\n\n /*!\n @brief reads a UBJSON string\n\n This function is either called after reading the 'S' byte explicitly\n indicating a string, or in case of an object key where the 'S' byte can be\n left out.\n\n @param[out] result created string\n @param[in] get_char whether a new character should be retrieved from the\n input (true, default) or whether the last read\n character should be considered instead\n\n @return whether string creation completed\n */\n bool get_ubjson_string(string_t& result, const bool get_char = true)\n {\n if (get_char)\n {\n // no get_ignore_noop() here: the byte read next must be a string\n // length type specification, and a no-op ('N') is not valid in\n // that position. No-ops at positions where a value may appear are\n // already consumed by the callers via get_ignore_noop().\n get();\n }\n\n if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format, \"value\")))\n {\n return false;\n }\n\n switch (current)\n {\n case 'U':\n {\n std::uint8_t len{};\n return get_number(input_format, len) && get_string(input_format, len, result);\n }\n\n case 'i':\n {\n std::int8_t len{};\n return get_number(input_format, len) && check_ubjson_string_length(len) && get_string(input_format, len, result);\n }\n\n case 'I':\n {\n std::int16_t len{};\n return get_number(input_format, len) && check_ubjson_string_length(len) && get_string(input_format, len, result);\n }\n\n case 'l':\n {\n std::int32_t len{};\n return get_number(input_format, len) && check_ubjson_string_length(len) && get_string(input_format, len, result);\n }\n\n case 'L':\n {\n std::int64_t len{};\n return get_number(input_format, len) && check_ubjson_string_length(len) && get_string(input_format, len, result);\n }\n\n case 'u':\n {\n if (input_format != input_format_t::bjdata)\n {\n break;\n }\n std::uint16_t len{};\n return get_number(input_format, len) && get_string(input_format, len, result);\n }\n\n case 'm':\n {\n if (input_format != input_format_t::bjdata)\n {\n break;\n }\n std::uint32_t len{};\n return get_number(input_format, len) && get_string(input_format, len, result);\n }\n\n case 'M':\n {\n if (input_format != input_format_t::bjdata)\n {\n break;\n }\n std::uint64_t len{};\n return get_number(input_format, len) && get_string(input_format, len, result);\n }\n\n default:\n break;\n }\n auto last_token = get_token_string();\n std::string message;\n\n if (input_format != input_format_t::bjdata)\n {\n message = \"expected length type specification (U, i, I, l, L); last byte: 0x\" + last_token;\n }\n else\n {\n message = \"expected length type specification (U, i, u, I, m, l, M, L); last byte: 0x\" + last_token;\n }\n return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format, message, \"string\"), nullptr));\n }\n\n /*!\n @param[out] dim an integer vector storing the ND array dimensions\n @return whether reading ND array size vector is successful\n */\n bool get_ubjson_ndarray_size(std::vector& dim)\n {\n std::pair size_and_type;\n size_t dimlen = 0;\n bool no_ndarray = true;\n\n if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type, no_ndarray)))\n {\n return false;\n }\n\n if (size_and_type.first != npos)\n {\n if (size_and_type.second != 0)\n {\n if (size_and_type.second != 'N')\n {\n for (std::size_t i = 0; i < size_and_type.first; ++i)\n {\n if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_value(dimlen, no_ndarray, size_and_type.second)))\n {\n return false;\n }\n dim.push_back(dimlen);\n }\n }\n }\n else\n {\n for (std::size_t i = 0; i < size_and_type.first; ++i)\n {\n if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_value(dimlen, no_ndarray)))\n {\n return false;\n }\n dim.push_back(dimlen);\n }\n }\n }\n else\n {\n while (current != ']')\n {\n if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_value(dimlen, no_ndarray, current)))\n {\n return false;\n }\n dim.push_back(dimlen);\n get_ignore_noop();\n }\n }\n return true;\n }\n\n /*!\n @param[out] result determined size\n @param[in,out] is_ndarray for input, `true` means already inside an ndarray vector\n or ndarray dimension is not allowed; `false` means ndarray\n is allowed; for output, `true` means an ndarray is found;\n is_ndarray can only return `true` when its initial value\n is `false`\n @param[in] prefix type marker if already read, otherwise set to 0\n\n @return whether size determination completed\n */\n bool get_ubjson_size_value(std::size_t& result, bool& is_ndarray, char_int_type prefix = 0)\n {\n if (prefix == 0)\n {\n prefix = get_ignore_noop();\n }\n\n switch (prefix)\n {\n case 'U':\n {\n std::uint8_t number{};\n if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number)))\n {\n return false;\n }\n result = static_cast(number);\n return true;\n }\n\n case 'i':\n {\n std::int8_t number{};\n if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number)))\n {\n return false;\n }\n if (number < 0)\n {\n return sax->parse_error(chars_read, get_token_string(), parse_error::create(113, chars_read,\n exception_message(input_format, \"count in an optimized container must be positive\", \"size\"), nullptr));\n }\n result = static_cast(number); // NOLINT(bugprone-signed-char-misuse,cert-str34-c): number is not a char\n return true;\n }\n\n case 'I':\n {\n std::int16_t number{};\n if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number)))\n {\n return false;\n }\n if (number < 0)\n {\n return sax->parse_error(chars_read, get_token_string(), parse_error::create(113, chars_read,\n exception_message(input_format, \"count in an optimized container must be positive\", \"size\"), nullptr));\n }\n result = static_cast(number);\n return true;\n }\n\n case 'l':\n {\n std::int32_t number{};\n if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number)))\n {\n return false;\n }\n if (number < 0)\n {\n return sax->parse_error(chars_read, get_token_string(), parse_error::create(113, chars_read,\n exception_message(input_format, \"count in an optimized container must be positive\", \"size\"), nullptr));\n }\n result = static_cast(number);\n return true;\n }\n\n case 'L':\n {\n std::int64_t number{};\n if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number)))\n {\n return false;\n }\n if (number < 0)\n {\n return sax->parse_error(chars_read, get_token_string(), parse_error::create(113, chars_read,\n exception_message(input_format, \"count in an optimized container must be positive\", \"size\"), nullptr));\n }\n if (!value_in_range_of(number))\n {\n return sax->parse_error(chars_read, get_token_string(), out_of_range::create(408,\n exception_message(input_format, \"integer value overflow\", \"size\"), nullptr));\n }\n result = static_cast(number);\n return true;\n }\n\n case 'u':\n {\n if (input_format != input_format_t::bjdata)\n {\n break;\n }\n std::uint16_t number{};\n if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number)))\n {\n return false;\n }\n result = static_cast(number);\n return true;\n }\n\n case 'm':\n {\n if (input_format != input_format_t::bjdata)\n {\n break;\n }\n std::uint32_t number{};\n if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number)))\n {\n return false;\n }\n result = conditional_static_cast(number);\n return true;\n }\n\n case 'M':\n {\n if (input_format != input_format_t::bjdata)\n {\n break;\n }\n std::uint64_t number{};\n if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number)))\n {\n return false;\n }\n if (!value_in_range_of(number))\n {\n return sax->parse_error(chars_read, get_token_string(), out_of_range::create(408,\n exception_message(input_format, \"integer value overflow\", \"size\"), nullptr));\n }\n result = detail::conditional_static_cast(number);\n return true;\n }\n\n case '[':\n {\n if (input_format != input_format_t::bjdata)\n {\n break;\n }\n if (is_ndarray) // ndarray dimensional vector can only contain integers and cannot embed another array\n {\n return sax->parse_error(chars_read, get_token_string(), parse_error::create(113, chars_read, exception_message(input_format, \"ndarray dimensional vector is not allowed\", \"size\"), nullptr));\n }\n std::vector dim;\n if (JSON_HEDLEY_UNLIKELY(!get_ubjson_ndarray_size(dim)))\n {\n return false;\n }\n if (dim.size() == 1 || (dim.size() == 2 && dim.at(0) == 1)) // return normal array size if 1D row vector\n {\n result = dim.at(dim.size() - 1);\n return true;\n }\n if (!dim.empty()) // if ndarray, convert to an object in JData annotated array format\n {\n for (auto i : dim) // test if any dimension in an ndarray is 0, if so, return a 1D empty container\n {\n if ( i == 0 )\n {\n result = 0;\n return true;\n }\n }\n\n string_t key = \"_ArraySize_\";\n if (JSON_HEDLEY_UNLIKELY(!sax->start_object(3) || !sax->key(key) || !sax->start_array(dim.size())))\n {\n return false;\n }\n result = 1;\n for (auto i : dim)\n {\n // Pre-multiplication overflow check: if i > 0 and result > SIZE_MAX/i, then result*i would overflow.\n // This check must happen before multiplication since overflow detection after the fact is unreliable\n // as modular arithmetic can produce any value, not just 0 or SIZE_MAX.\n if (JSON_HEDLEY_UNLIKELY(i > 0 && result > (std::numeric_limits::max)() / i))\n {\n return sax->parse_error(chars_read, get_token_string(), out_of_range::create(408, exception_message(input_format, \"excessive ndarray size caused overflow\", \"size\"), nullptr));\n }\n result *= i;\n // Additional post-multiplication check to catch any edge cases the pre-check might miss\n if (result == 0 || result == npos)\n {\n return sax->parse_error(chars_read, get_token_string(), out_of_range::create(408, exception_message(input_format, \"excessive ndarray size caused overflow\", \"size\"), nullptr));\n }\n if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(static_cast(i))))\n {\n return false;\n }\n }\n is_ndarray = true;\n return sax->end_array();\n }\n result = 0;\n return true;\n }\n\n default:\n break;\n }\n auto last_token = get_token_string();\n std::string message;\n\n if (input_format != input_format_t::bjdata)\n {\n message = \"expected length type specification (U, i, I, l, L) after '#'; last byte: 0x\" + last_token;\n }\n else\n {\n message = \"expected length type specification (U, i, u, I, m, l, M, L) after '#'; last byte: 0x\" + last_token;\n }\n return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format, message, \"size\"), nullptr));\n }\n\n /*!\n @brief determine the type and size for a container\n\n In the optimized UBJSON format, a type and a size can be provided to allow\n for a more compact representation.\n\n @param[out] result pair of the size and the type\n @param[in] inside_ndarray whether the parser is parsing an ND array dimensional vector\n\n @return whether pair creation completed\n */\n bool get_ubjson_size_type(std::pair& result, bool inside_ndarray = false)\n {\n result.first = npos; // size\n result.second = 0; // type\n bool is_ndarray = false;\n\n get_ignore_noop();\n\n if (current == '$')\n {\n result.second = get(); // must not ignore 'N', because 'N' maybe the type\n if (input_format == input_format_t::bjdata\n && JSON_HEDLEY_UNLIKELY(std::binary_search(bjd_optimized_type_markers.begin(), bjd_optimized_type_markers.end(), result.second)))\n {\n auto last_token = get_token_string();\n return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read,\n exception_message(input_format, concat(\"marker 0x\", last_token, \" is not a permitted optimized array type\"), \"type\"), nullptr));\n }\n\n if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format, \"type\")))\n {\n return false;\n }\n\n get_ignore_noop();\n if (JSON_HEDLEY_UNLIKELY(current != '#'))\n {\n if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format, \"value\")))\n {\n return false;\n }\n auto last_token = get_token_string();\n return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read,\n exception_message(input_format, concat(\"expected '#' after type information; last byte: 0x\", last_token), \"size\"), nullptr));\n }\n\n const bool is_error = get_ubjson_size_value(result.first, is_ndarray);\n if (input_format == input_format_t::bjdata && is_ndarray)\n {\n if (inside_ndarray)\n {\n return sax->parse_error(chars_read, get_token_string(), parse_error::create(112, chars_read,\n exception_message(input_format, \"ndarray can not be recursive\", \"size\"), nullptr));\n }\n result.second |= (1 << 8); // use bit 8 to indicate ndarray, all UBJSON and BJData markers should be ASCII letters\n }\n return is_error;\n }\n\n if (current == '#')\n {\n const bool is_error = get_ubjson_size_value(result.first, is_ndarray);\n if (input_format == input_format_t::bjdata && is_ndarray)\n {\n return sax->parse_error(chars_read, get_token_string(), parse_error::create(112, chars_read,\n exception_message(input_format, \"ndarray requires both type and size\", \"size\"), nullptr));\n }\n return is_error;\n }\n\n return true;\n }\n\n /*!\n @param prefix the previously read or set type prefix\n @return whether value creation completed\n */\n bool get_ubjson_value(const char_int_type prefix)\n {\n switch (prefix)\n {\n case char_traits::eof(): // EOF\n return unexpect_eof(input_format, \"value\");\n\n case 'T': // true\n return sax->boolean(true);\n case 'F': // false\n return sax->boolean(false);\n\n case 'Z': // null\n return sax->null();\n\n case 'B': // byte\n {\n if (input_format != input_format_t::bjdata)\n {\n break;\n }\n std::uint8_t number{};\n return get_number(input_format, number) && sax->number_unsigned(number);\n }\n\n case 'U':\n {\n std::uint8_t number{};\n return get_number(input_format, number) && sax->number_unsigned(number);\n }\n\n case 'i':\n {\n std::int8_t number{};\n return get_number(input_format, number) && sax->number_integer(number);\n }\n\n case 'I':\n {\n std::int16_t number{};\n return get_number(input_format, number) && sax->number_integer(number);\n }\n\n case 'l':\n {\n std::int32_t number{};\n return get_number(input_format, number) && sax->number_integer(number);\n }\n\n case 'L':\n {\n std::int64_t number{};\n return get_number(input_format, number) && sax->number_integer(number);\n }\n\n case 'u':\n {\n if (input_format != input_format_t::bjdata)\n {\n break;\n }\n std::uint16_t number{};\n return get_number(input_format, number) && sax->number_unsigned(number);\n }\n\n case 'm':\n {\n if (input_format != input_format_t::bjdata)\n {\n break;\n }\n std::uint32_t number{};\n return get_number(input_format, number) && sax->number_unsigned(number);\n }\n\n case 'M':\n {\n if (input_format != input_format_t::bjdata)\n {\n break;\n }\n std::uint64_t number{};\n return get_number(input_format, number) && sax->number_unsigned(number);\n }\n\n case 'h':\n {\n if (input_format != input_format_t::bjdata)\n {\n break;\n }\n const auto byte1_raw = get();\n if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format, \"number\")))\n {\n return false;\n }\n const auto byte2_raw = get();\n if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format, \"number\")))\n {\n return false;\n }\n\n const auto byte1 = static_cast(byte1_raw);\n const auto byte2 = static_cast(byte2_raw);\n\n // Code from RFC 8949, Appendix D, Figure 3:\n // As half-precision floating-point numbers were only added\n // to IEEE 754 in 2008, today's programming platforms often\n // still only have limited support for them. It is very\n // easy to include at least decoding support for them even\n // without such support. An example of a small decoder for\n // half-precision floating-point numbers in the C language\n // is shown in Fig. 3.\n const auto half = static_cast((byte2 << 8u) + byte1);\n const double val = [&half]\n {\n const int exp = (half >> 10u) & 0x1Fu;\n const unsigned int mant = half & 0x3FFu;\n JSON_ASSERT(exp <= 31);\n JSON_ASSERT(mant <= 1023);\n switch (exp)\n {\n case 0:\n return std::ldexp(mant, -24);\n case 31:\n return (mant == 0)\n ? std::numeric_limits::infinity()\n : std::numeric_limits::quiet_NaN();\n default:\n return std::ldexp(mant + 1024, exp - 25);\n }\n }();\n return sax->number_float((half & 0x8000u) != 0\n ? static_cast(-val)\n : static_cast(val), \"\");\n }\n\n case 'd':\n {\n float number{};\n return get_number(input_format, number) && sax->number_float(static_cast(number), \"\");\n }\n\n case 'D':\n {\n double number{};\n return get_number(input_format, number) && sax->number_float(static_cast(number), \"\");\n }\n\n case 'H':\n {\n return get_ubjson_high_precision_number();\n }\n\n case 'C': // char\n {\n get();\n if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format, \"char\")))\n {\n return false;\n }\n if (JSON_HEDLEY_UNLIKELY(current > 127))\n {\n auto last_token = get_token_string();\n return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read,\n exception_message(input_format, concat(\"byte after 'C' must be in range 0x00..0x7F; last byte: 0x\", last_token), \"char\"), nullptr));\n }\n string_t s(1, static_cast(current));\n return sax->string(s);\n }\n\n case 'S': // string\n {\n string_t s;\n return get_ubjson_string(s) && sax->string(s);\n }\n\n case '[': // array\n return get_ubjson_array();\n\n case '{': // object\n return get_ubjson_object();\n\n default: // anything else\n break;\n }\n auto last_token = get_token_string();\n return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format, \"invalid byte: 0x\" + last_token, \"value\"), nullptr));\n }\n\n /*!\n @return whether array creation completed\n */\n bool get_ubjson_array()\n {\n std::pair size_and_type;\n if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type)))\n {\n return false;\n }\n\n // if bit-8 of size_and_type.second is set to 1, encode bjdata ndarray as an object in JData annotated array format (https://github.com/NeuroJSON/jdata):\n // {\"_ArrayType_\" : \"typeid\", \"_ArraySize_\" : [n1, n2, ...], \"_ArrayData_\" : [v1, v2, ...]}\n\n if (input_format == input_format_t::bjdata && size_and_type.first != npos && (size_and_type.second & (1 << 8)) != 0)\n {\n size_and_type.second &= ~(static_cast(1) << 8); // use bit 8 to indicate ndarray, here we remove the bit to restore the type marker\n auto it = std::lower_bound(bjd_types_map.begin(), bjd_types_map.end(), size_and_type.second, [](const bjd_type & p, char_int_type t)\n {\n return p.first < t;\n });\n string_t key = \"_ArrayType_\";\n if (JSON_HEDLEY_UNLIKELY(it == bjd_types_map.end() || it->first != size_and_type.second))\n {\n auto last_token = get_token_string();\n return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read,\n exception_message(input_format, \"invalid byte: 0x\" + last_token, \"type\"), nullptr));\n }\n\n string_t type = it->second; // sax->string() takes a reference\n if (JSON_HEDLEY_UNLIKELY(!sax->key(key) || !sax->string(type)))\n {\n return false;\n }\n\n if (size_and_type.second == 'C' || size_and_type.second == 'B')\n {\n size_and_type.second = 'U';\n }\n\n key = \"_ArrayData_\";\n if (JSON_HEDLEY_UNLIKELY(!sax->key(key) || !sax->start_array(size_and_type.first) ))\n {\n return false;\n }\n\n for (std::size_t i = 0; i < size_and_type.first; ++i)\n {\n if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second)))\n {\n return false;\n }\n }\n\n return (sax->end_array() && sax->end_object());\n }\n\n // If BJData type marker is 'B' decode as binary\n if (input_format == input_format_t::bjdata && size_and_type.first != npos && size_and_type.second == 'B')\n {\n binary_t result;\n return get_binary(input_format, size_and_type.first, result) && sax->binary(result);\n }\n\n if (size_and_type.first != npos)\n {\n if (JSON_HEDLEY_UNLIKELY(!sax->start_array(size_and_type.first)))\n {\n return false;\n }\n\n if (size_and_type.second != 0)\n {\n if (size_and_type.second != 'N')\n {\n for (std::size_t i = 0; i < size_and_type.first; ++i)\n {\n if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second)))\n {\n return false;\n }\n }\n }\n }\n else\n {\n for (std::size_t i = 0; i < size_and_type.first; ++i)\n {\n if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))\n {\n return false;\n }\n }\n }\n }\n else\n {\n if (JSON_HEDLEY_UNLIKELY(!sax->start_array(detail::unknown_size())))\n {\n return false;\n }\n\n while (current != ']')\n {\n if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal(false)))\n {\n return false;\n }\n get_ignore_noop();\n }\n }\n\n return sax->end_array();\n }\n\n /*!\n @return whether object creation completed\n */\n bool get_ubjson_object()\n {\n std::pair size_and_type;\n if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type)))\n {\n return false;\n }\n\n // do not accept ND-array size in objects in BJData\n if (input_format == input_format_t::bjdata && size_and_type.first != npos && (size_and_type.second & (1 << 8)) != 0)\n {\n auto last_token = get_token_string();\n return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read,\n exception_message(input_format, \"BJData object does not support ND-array size in optimized format\", \"object\"), nullptr));\n }\n\n string_t key;\n if (size_and_type.first != npos)\n {\n if (JSON_HEDLEY_UNLIKELY(!sax->start_object(size_and_type.first)))\n {\n return false;\n }\n\n if (size_and_type.second != 0)\n {\n for (std::size_t i = 0; i < size_and_type.first; ++i)\n {\n if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key)))\n {\n return false;\n }\n if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second)))\n {\n return false;\n }\n key.clear();\n }\n }\n else\n {\n for (std::size_t i = 0; i < size_and_type.first; ++i)\n {\n if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key)))\n {\n return false;\n }\n if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))\n {\n return false;\n }\n key.clear();\n }\n }\n }\n else\n {\n if (JSON_HEDLEY_UNLIKELY(!sax->start_object(detail::unknown_size())))\n {\n return false;\n }\n\n while (current != '}')\n {\n if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key, false) || !sax->key(key)))\n {\n return false;\n }\n if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))\n {\n return false;\n }\n get_ignore_noop();\n key.clear();\n }\n }\n\n return sax->end_object();\n }\n\n // Note, no reader for UBJSON binary types is implemented because they do\n // not exist\n\n bool get_ubjson_high_precision_number()\n {\n // get the size of the following number string\n std::size_t size{};\n bool no_ndarray = true;\n auto res = get_ubjson_size_value(size, no_ndarray);\n if (JSON_HEDLEY_UNLIKELY(!res))\n {\n return res;\n }\n\n // get number string\n std::vector number_vector;\n for (std::size_t i = 0; i < size; ++i)\n {\n get();\n if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format, \"number\")))\n {\n return false;\n }\n number_vector.push_back(static_cast(current));\n }\n\n // parse number string\n using ia_type = decltype(detail::input_adapter(number_vector));\n auto number_lexer = detail::lexer(detail::input_adapter(number_vector), false);\n const auto result_number = number_lexer.scan();\n const auto number_string = number_lexer.get_token_string();\n const auto result_remainder = number_lexer.scan();\n\n using token_type = typename detail::lexer_base::token_type;\n\n if (JSON_HEDLEY_UNLIKELY(result_remainder != token_type::end_of_input))\n {\n return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read,\n exception_message(input_format, concat(\"invalid number text: \", number_lexer.get_token_string()), \"high-precision number\"), nullptr));\n }\n\n switch (result_number)\n {\n case token_type::value_integer:\n return sax->number_integer(number_lexer.get_number_integer());\n case token_type::value_unsigned:\n return sax->number_unsigned(number_lexer.get_number_unsigned());\n case token_type::value_float:\n {\n const auto parsed_float = number_lexer.get_number_float();\n if (JSON_HEDLEY_UNLIKELY(!std::isfinite(parsed_float)))\n {\n return sax->parse_error(\n chars_read,\n number_string,\n out_of_range::create(406, concat(\"number overflow parsing '\", number_string, '\\''), nullptr));\n }\n return sax->number_float(parsed_float, std::move(number_string));\n }\n case token_type::uninitialized:\n case token_type::literal_true:\n case token_type::literal_false:\n case token_type::literal_null:\n case token_type::value_string:\n case token_type::begin_array:\n case token_type::begin_object:\n case token_type::end_array:\n case token_type::end_object:\n case token_type::name_separator:\n case token_type::value_separator:\n case token_type::parse_error:\n case token_type::end_of_input:\n case token_type::literal_or_value:\n default:\n return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read,\n exception_message(input_format, concat(\"invalid number text: \", number_lexer.get_token_string()), \"high-precision number\"), nullptr));\n }\n }\n\n ///////////////////////\n // Utility functions //\n ///////////////////////\n\n /*!\n @brief get next character from the input\n\n This function provides the interface to the used input adapter. It does\n not throw in case the input reached EOF, but returns a -'ve valued\n `char_traits::eof()` in that case.\n\n @return character read from the input\n */\n char_int_type get()\n {\n ++chars_read;\n return current = ia.get_character();\n }\n\n /*!\n @brief get_to read into a primitive type\n\n This function provides the interface to the used input adapter. It does\n not throw in case the input reached EOF, but returns false instead\n\n @return bool, whether the read was successful\n */\n template\n bool get_to(T& dest, const input_format_t format, const char* context)\n {\n auto new_chars_read = ia.get_elements(&dest);\n chars_read += new_chars_read;\n if (JSON_HEDLEY_UNLIKELY(new_chars_read < sizeof(T)))\n {\n // in case of failure, advance position by 1 to report the failing location\n ++chars_read;\n sax->parse_error(chars_read, \"\", parse_error::create(110, chars_read, exception_message(format, \"unexpected end of input\", context), nullptr));\n return false;\n }\n return true;\n }\n\n /*!\n @return character read from the input after ignoring all 'N' entries\n */\n char_int_type get_ignore_noop()\n {\n do\n {\n get();\n }\n while (current == 'N');\n\n return current;\n }\n\n template\n static void byte_swap(NumberType& number)\n {\n constexpr std::size_t sz = sizeof(number);\n#ifdef __cpp_lib_byteswap\n if constexpr (sz == 1)\n {\n return;\n }\n else if constexpr(std::is_integral_v)\n {\n number = std::byteswap(number);\n return;\n }\n else\n {\n#endif\n auto* ptr = reinterpret_cast(&number);\n for (std::size_t i = 0; i < sz / 2; ++i)\n {\n std::swap(ptr[i], ptr[sz - i - 1]);\n }\n#ifdef __cpp_lib_byteswap\n }\n#endif\n }\n\n /*\n @brief read a number from the input\n\n @tparam NumberType the type of the number\n @param[in] format the current format (for diagnostics)\n @param[out] result number of type @a NumberType\n\n @return whether conversion completed\n\n @note This function needs to respect the system's endianness, because\n bytes in CBOR, MessagePack, and UBJSON are stored in network order\n (big endian) and therefore need reordering on little endian systems.\n On the other hand, BSON and BJData use little endian and should reorder\n on big endian systems.\n */\n template\n bool get_number(const input_format_t format, NumberType& result)\n {\n // read in the original format\n\n if (JSON_HEDLEY_UNLIKELY(!get_to(result, format, \"number\")))\n {\n return false;\n }\n if (is_little_endian != (InputIsLittleEndian || format == input_format_t::bjdata))\n {\n byte_swap(result);\n }\n return true;\n }\n\n /*!\n @brief create a string by reading characters from the input\n\n @tparam NumberType the type of the number\n @param[in] format the current format (for diagnostics)\n @param[in] len number of characters to read\n @param[out] result string created by reading @a len bytes\n\n @return whether string creation completed\n\n @note We can not reserve @a len bytes for the result, because @a len\n may be too large. Usually, @ref unexpect_eof() detects the end of\n the input before we run out of string memory.\n */\n template\n bool get_string(const input_format_t format,\n const NumberType len,\n string_t& result)\n {\n return get_bytes(format, len, \"string\", result);\n }\n\n /*!\n @brief create a byte array by reading bytes from the input\n\n @tparam NumberType the type of the number\n @param[in] format the current format (for diagnostics)\n @param[in] len number of bytes to read\n @param[out] result byte array created by reading @a len bytes\n\n @return whether byte array creation completed\n\n @note We can not reserve @a len bytes for the result, because @a len\n may be too large. Usually, @ref unexpect_eof() detects the end of\n the input before we run out of memory.\n */\n template\n bool get_binary(const input_format_t format,\n const NumberType len,\n binary_t& result)\n {\n return get_bytes(format, len, \"binary\", result);\n }\n\n /*!\n @brief read @a len bytes from the input into a string or byte container\n\n @tparam NumberType the type of the length\n @tparam ContainerType the destination container (string_t or binary_t)\n @param[in] format the current format (for diagnostics)\n @param[in] len number of bytes to read\n @param[in] context further context information (for diagnostics)\n @param[out] result container the bytes are appended to\n\n @return whether reading completed\n\n @note We cannot reserve @a len bytes for the result up front, because\n @a len may be far larger than the actual input. Instead we read in\n bounded chunks, so the peak allocation is capped regardless of the\n claimed length while the per-byte loop is replaced by block copies\n (a std::memcpy for contiguous inputs). @ref unexpect_eof() still\n detects a premature end of input.\n */\n template\n bool get_bytes(const input_format_t format,\n NumberType len,\n const char* context,\n ContainerType& result)\n {\n // upper bound on the number of bytes read (and allocated) per chunk\n constexpr std::size_t chunk_size = 4096;\n\n while (len > 0)\n {\n // number of bytes to read this iteration: min(chunk_size, len),\n // computed without truncating chunk_size to a narrow NumberType\n const std::size_t wanted = (static_cast(len) < static_cast(chunk_size))\n ? static_cast(len)\n : chunk_size;\n const std::size_t old_size = result.size();\n result.resize(old_size + wanted);\n // resize() is required to make size() exactly old_size + wanted;\n // that is the room get_elements() is allowed to write into\n JSON_ASSERT(result.size() == old_size + wanted);\n const std::size_t bytes_read = ia.get_elements(&result[old_size], wanted);\n chars_read += bytes_read;\n if (JSON_HEDLEY_UNLIKELY(bytes_read < wanted))\n {\n // premature end of input: shrink to what was actually read and\n // report the failure at the first missing byte (same position\n // accounting as get_to() for partial number reads)\n result.resize(old_size + bytes_read);\n ++chars_read;\n current = char_traits::eof();\n return unexpect_eof(format, context);\n }\n // a full chunk was read; get_elements() never returns more than requested\n JSON_ASSERT(bytes_read == wanted);\n len = static_cast(len - static_cast(wanted));\n }\n return true;\n }\n\n /*!\n @param[in] format the current format (for diagnostics)\n @param[in] context further context information (for diagnostics)\n @return whether the last read character is not EOF\n */\n JSON_HEDLEY_NON_NULL(3)\n bool unexpect_eof(const input_format_t format, const char* context) const\n {\n if (JSON_HEDLEY_UNLIKELY(current == char_traits::eof()))\n {\n return sax->parse_error(chars_read, \"\",\n parse_error::create(110, chars_read, exception_message(format, \"unexpected end of input\", context), nullptr));\n }\n return true;\n }\n\n /*!\n @return a string representation of the last read byte\n */\n std::string get_token_string() const\n {\n std::array cr{{}};\n static_cast((std::snprintf)(cr.data(), cr.size(), \"%.2hhX\", static_cast(current))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg)\n return std::string{cr.data()};\n }\n\n /*!\n @param[in] format the current format\n @param[in] detail a detailed error message\n @param[in] context further context information\n @return a message string to use in the parse_error exceptions\n */\n std::string exception_message(const input_format_t format,\n const std::string& detail,\n const std::string& context) const\n {\n std::string error_msg = \"syntax error while parsing \";\n\n switch (format)\n {\n case input_format_t::cbor:\n error_msg += \"CBOR\";\n break;\n\n case input_format_t::msgpack:\n error_msg += \"MessagePack\";\n break;\n\n case input_format_t::ubjson:\n error_msg += \"UBJSON\";\n break;\n\n case input_format_t::bson:\n error_msg += \"BSON\";\n break;\n\n case input_format_t::bjdata:\n error_msg += \"BJData\";\n break;\n\n case input_format_t::json: // LCOV_EXCL_LINE\n default: // LCOV_EXCL_LINE\n JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE\n }\n\n return concat(error_msg, ' ', context, \": \", detail);\n }\n\n private:\n static JSON_INLINE_VARIABLE constexpr std::size_t npos = detail::unknown_size();\n\n /// input adapter\n InputAdapterType ia;\n\n /// the current character\n char_int_type current = char_traits::eof();\n\n /// the number of characters read\n std::size_t chars_read = 0;\n\n /// whether we can assume little endianness\n const bool is_little_endian = little_endianness();\n\n /// input format\n const input_format_t input_format = input_format_t::json;\n\n /// the SAX parser\n json_sax_t* sax = nullptr;\n\n // excluded markers in bjdata optimized type\n#define JSON_BINARY_READER_MAKE_BJD_OPTIMIZED_TYPE_MARKERS_ \\\n make_array('F', 'H', 'N', 'S', 'T', 'Z', '[', '{')\n\n#define JSON_BINARY_READER_MAKE_BJD_TYPES_MAP_ \\\n make_array( \\\n bjd_type{'B', \"byte\"}, \\\n bjd_type{'C', \"char\"}, \\\n bjd_type{'D', \"double\"}, \\\n bjd_type{'I', \"int16\"}, \\\n bjd_type{'L', \"int64\"}, \\\n bjd_type{'M', \"uint64\"}, \\\n bjd_type{'U', \"uint8\"}, \\\n bjd_type{'d', \"single\"}, \\\n bjd_type{'i', \"int8\"}, \\\n bjd_type{'l', \"int32\"}, \\\n bjd_type{'m', \"uint32\"}, \\\n bjd_type{'u', \"uint16\"})\n\n JSON_PRIVATE_UNLESS_TESTED:\n // lookup tables\n // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)\n const decltype(JSON_BINARY_READER_MAKE_BJD_OPTIMIZED_TYPE_MARKERS_) bjd_optimized_type_markers =\n JSON_BINARY_READER_MAKE_BJD_OPTIMIZED_TYPE_MARKERS_;\n\n using bjd_type = std::pair;\n // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)\n const decltype(JSON_BINARY_READER_MAKE_BJD_TYPES_MAP_) bjd_types_map =\n JSON_BINARY_READER_MAKE_BJD_TYPES_MAP_;\n\n#undef JSON_BINARY_READER_MAKE_BJD_OPTIMIZED_TYPE_MARKERS_\n#undef JSON_BINARY_READER_MAKE_BJD_TYPES_MAP_\n};\n\n#ifndef JSON_HAS_CPP_17\n template\n constexpr std::size_t binary_reader::npos;\n#endif\n\n} // namespace detail\nNLOHMANN_JSON_NAMESPACE_END", "messages": null, "tools": null} {"id": "731aea27e750e1d5", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/plugin-legacy/src/__tests__/index.spec.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 1585, "sha256": "26c3a21edac5fdef7380d7065912cc5d7b257da7297bbe1bf501f7d3f89a5a76", "text": "import { describe, expect, test } from 'vitest'\nimport { modulePreloadLinkRE } from '../index'\n\ndescribe('modulePreloadLinkRE', () => {\n const matches: Array<[string, string]> = [\n ['rel first', ''],\n [\n 'rel after other attributes',\n '',\n ],\n ['rel only', ''],\n ['self-closing', ''],\n ['self-closing with space', ''],\n ['single quotes', \"\"],\n [\n 'attributes across multiple lines',\n '',\n ],\n ]\n\n for (const [name, html] of matches) {\n test(`matches: ${name}`, () => {\n expect(html.replace(modulePreloadLinkRE, '')).toBe('')\n })\n }\n\n const nonMatches: Array<[string, string]> = [\n ['tag name with suffix', ''],\n ['custom element with hyphen', ''],\n ['bare link tag', ''],\n ['stylesheet link', ''],\n ['preload (not modulepreload)', ''],\n [\n 'attribute name ending in rel',\n '',\n ],\n ['mismatched quotes', ``],\n ]\n\n for (const [name, html] of nonMatches) {\n test(`does not match: ${name}`, () => {\n expect(html.replace(modulePreloadLinkRE, '')).toBe(html)\n })\n }\n})", "messages": null, "tools": null} {"id": "73c33dad1f77d1bd", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/thirdparty/Fuzzer/FuzzerUtil.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 6085, "sha256": "f3d1fd7774bebcbcbdfbce6c47bbe0a915b5dba16addf9bc2cf159db45f38af4", "text": "//===- FuzzerUtil.cpp - Misc utils ----------------------------------------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n// Misc utils.\n//===----------------------------------------------------------------------===//\n\n#include \"FuzzerUtil.h\"\n#include \"FuzzerIO.h\"\n#include \"FuzzerInternal.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace fuzzer {\n\nvoid PrintHexArray(const uint8_t *Data, size_t Size,\n const char *PrintAfter) {\n for (size_t i = 0; i < Size; i++)\n Printf(\"0x%x,\", (unsigned)Data[i]);\n Printf(\"%s\", PrintAfter);\n}\n\nvoid Print(const Unit &v, const char *PrintAfter) {\n PrintHexArray(v.data(), v.size(), PrintAfter);\n}\n\nvoid PrintASCIIByte(uint8_t Byte) {\n if (Byte == '\\\\')\n Printf(\"\\\\\\\\\");\n else if (Byte == '\"')\n Printf(\"\\\\\\\"\");\n else if (Byte >= 32 && Byte < 127)\n Printf(\"%c\", Byte);\n else\n Printf(\"\\\\x%02x\", Byte);\n}\n\nvoid PrintASCII(const uint8_t *Data, size_t Size, const char *PrintAfter) {\n for (size_t i = 0; i < Size; i++)\n PrintASCIIByte(Data[i]);\n Printf(\"%s\", PrintAfter);\n}\n\nvoid PrintASCII(const Unit &U, const char *PrintAfter) {\n PrintASCII(U.data(), U.size(), PrintAfter);\n}\n\nbool ToASCII(uint8_t *Data, size_t Size) {\n bool Changed = false;\n for (size_t i = 0; i < Size; i++) {\n uint8_t &X = Data[i];\n auto NewX = X;\n NewX &= 127;\n if (!isspace(NewX) && !isprint(NewX))\n NewX = ' ';\n Changed |= NewX != X;\n X = NewX;\n }\n return Changed;\n}\n\nbool IsASCII(const Unit &U) { return IsASCII(U.data(), U.size()); }\n\nbool IsASCII(const uint8_t *Data, size_t Size) {\n for (size_t i = 0; i < Size; i++)\n if (!(isprint(Data[i]) || isspace(Data[i]))) return false;\n return true;\n}\n\nbool ParseOneDictionaryEntry(const std::string &Str, Unit *U) {\n U->clear();\n if (Str.empty()) return false;\n size_t L = 0, R = Str.size() - 1; // We are parsing the range [L,R].\n // Skip spaces from both sides.\n while (L < R && isspace(Str[L])) L++;\n while (R > L && isspace(Str[R])) R--;\n if (R - L < 2) return false;\n // Check the closing \"\n if (Str[R] != '\"') return false;\n R--;\n // Find the opening \"\n while (L < R && Str[L] != '\"') L++;\n if (L >= R) return false;\n assert(Str[L] == '\\\"');\n L++;\n assert(L <= R);\n for (size_t Pos = L; Pos <= R; Pos++) {\n uint8_t V = (uint8_t)Str[Pos];\n if (!isprint(V) && !isspace(V)) return false;\n if (V =='\\\\') {\n // Handle '\\\\'\n if (Pos + 1 <= R && (Str[Pos + 1] == '\\\\' || Str[Pos + 1] == '\"')) {\n U->push_back(Str[Pos + 1]);\n Pos++;\n continue;\n }\n // Handle '\\xAB'\n if (Pos + 3 <= R && Str[Pos + 1] == 'x'\n && isxdigit(Str[Pos + 2]) && isxdigit(Str[Pos + 3])) {\n char Hex[] = \"0xAA\";\n Hex[2] = Str[Pos + 2];\n Hex[3] = Str[Pos + 3];\n U->push_back(strtol(Hex, nullptr, 16));\n Pos += 3;\n continue;\n }\n return false; // Invalid escape.\n } else {\n // Any other character.\n U->push_back(V);\n }\n }\n return true;\n}\n\nbool ParseDictionaryFile(const std::string &Text, std::vector *Units) {\n if (Text.empty()) {\n Printf(\"ParseDictionaryFile: file does not exist or is empty\\n\");\n return false;\n }\n std::istringstream ISS(Text);\n Units->clear();\n Unit U;\n int LineNo = 0;\n std::string S;\n while (std::getline(ISS, S, '\\n')) {\n LineNo++;\n size_t Pos = 0;\n while (Pos < S.size() && isspace(S[Pos])) Pos++; // Skip spaces.\n if (Pos == S.size()) continue; // Empty line.\n if (S[Pos] == '#') continue; // Comment line.\n if (ParseOneDictionaryEntry(S, &U)) {\n Units->push_back(U);\n } else {\n Printf(\"ParseDictionaryFile: error in line %d\\n\\t\\t%s\\n\", LineNo,\n S.c_str());\n return false;\n }\n }\n return true;\n}\n\nstd::string Base64(const Unit &U) {\n static const char Table[] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"abcdefghijklmnopqrstuvwxyz\"\n \"0123456789+/\";\n std::string Res;\n size_t i;\n for (i = 0; i + 2 < U.size(); i += 3) {\n uint32_t x = (U[i] << 16) + (U[i + 1] << 8) + U[i + 2];\n Res += Table[(x >> 18) & 63];\n Res += Table[(x >> 12) & 63];\n Res += Table[(x >> 6) & 63];\n Res += Table[x & 63];\n }\n if (i + 1 == U.size()) {\n uint32_t x = (U[i] << 16);\n Res += Table[(x >> 18) & 63];\n Res += Table[(x >> 12) & 63];\n Res += \"==\";\n } else if (i + 2 == U.size()) {\n uint32_t x = (U[i] << 16) + (U[i + 1] << 8);\n Res += Table[(x >> 18) & 63];\n Res += Table[(x >> 12) & 63];\n Res += Table[(x >> 6) & 63];\n Res += \"=\";\n }\n return Res;\n}\n\nstd::string DescribePC(const char *SymbolizedFMT, uintptr_t PC) {\n if (!EF->__sanitizer_symbolize_pc) return \"\";\n char PcDescr[1024];\n EF->__sanitizer_symbolize_pc(reinterpret_cast(PC),\n SymbolizedFMT, PcDescr, sizeof(PcDescr));\n PcDescr[sizeof(PcDescr) - 1] = 0; // Just in case.\n return PcDescr;\n}\n\nvoid PrintPC(const char *SymbolizedFMT, const char *FallbackFMT, uintptr_t PC) {\n if (EF->__sanitizer_symbolize_pc)\n Printf(\"%s\", DescribePC(SymbolizedFMT, PC).c_str());\n else\n Printf(FallbackFMT, PC);\n}\n\nunsigned NumberOfCpuCores() {\n unsigned N = std::thread::hardware_concurrency();\n if (!N) {\n Printf(\"WARNING: std::thread::hardware_concurrency not well defined for \"\n \"your platform. Assuming CPU count of 1.\\n\");\n N = 1;\n }\n return N;\n}\n\nbool ExecuteCommandAndReadOutput(const std::string &Command, std::string *Out) {\n FILE *Pipe = OpenProcessPipe(Command.c_str(), \"r\");\n if (!Pipe) return false;\n char Buff[1024];\n size_t N;\n while ((N = fread(Buff, 1, sizeof(Buff), Pipe)) > 0)\n Out->append(Buff, N);\n return true;\n}\n\n} // namespace fuzzer", "messages": null, "tools": null} {"id": "7574919618b78836", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/api/json_pointer/index.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 2323, "sha256": "533e8264ff613de48ff80dd7ba309a634b15b8902cf1438867261c4e1de02e39", "text": "# nlohmann::json_pointer\n\n```cpp\ntemplate\nclass json_pointer;\n```\n\nA JSON pointer defines a string syntax for identifying a specific value within a JSON document. It can be used with\nfunctions [`at`](../basic_json/at.md) and [`operator[]`](../basic_json/operator%5B%5D.md). Furthermore, JSON pointers\nare the base for JSON patches.\n\n## Template parameters\n\n`RefStringType`\n: the string type used for the reference tokens making up the JSON pointer\n\n!!! warning \"Deprecation\"\n\n For backwards compatibility `RefStringType` may also be a specialization of [`basic_json`](../basic_json/index.md)\n in which case `string_t` will be deduced as [`basic_json::string_t`](../basic_json/string_t.md). This feature is\n deprecated and may be removed in a future major version.\n\n## Member types\n\n- [**string_t**](string_t.md) - the string type used for the reference tokens\n\n## Member functions\n\n- [(constructor)](json_pointer.md)\n- [**to_string**](to_string.md) - return a string representation of the JSON pointer\n- [**operator string_t**](operator_string_t.md) - return a string representation of the JSON pointer\n- [**operator==**](operator_eq.md) - compare: equal\n- [**operator!=**](operator_ne.md) - compare: not equal\n- [**operator/=**](operator_slasheq.md) - append to the end of the JSON pointer\n- [**operator/**](operator_slash.md) - create JSON Pointer by appending\n- [**parent_pointer**](parent_pointer.md) - returns the parent of this JSON pointer\n- [**pop_back**](pop_back.md) - remove the last reference token\n- [**back**](back.md) - return last reference token\n- [**push_back**](push_back.md) - append an unescaped token at the end of the pointer\n- [**pop_front**](pop_front.md) - remove the first reference token\n- [**front**](front.md) - return first reference token\n- [**push_front**](push_front.md) - append an unescaped token at the start of the pointer\n- [**empty**](empty.md) - return whether the pointer points to the root document\n\n## Literals\n\n- [**operator\"\"_json_pointer**](../operator_literal_json_pointer.md) - user-defined string literal for JSON pointers\n## See also\n\n- [RFC 6901](https://datatracker.ietf.org/doc/html/rfc6901)\n\n## Version history\n\n- Added in version 2.0.0.\n- Changed template parameter from `basic_json` to string type in version 3.11.0.", "messages": null, "tools": null} {"id": "75c67afb993795b4", "category": "code", "domain": "code", "source": "ripgrep", "license": "MIT OR Unlicense", "license_url": "https://spdx.org/licenses/MIT.html", "path": "crates/core/README.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/BurntSushi/ripgrep", "commit": "3fce3b5bb0236da2df6d99672afb8a719642eca7", "collector": "tools/harvest.py"}, "chars": 673, "sha256": "214e67761d6a41f8a2a901fe05063b34ed8144a500f2afd546fbce9e8b4b19c5", "text": "ripgrep core\n------------\nThis is the core ripgrep crate. In particular, `main.rs` is where the `main`\nfunction lives.\n\nMost of ripgrep core consists of two things:\n\n* The definition of the CLI interface, including docs for every flag.\n* Glue code that brings the `grep-matcher`, `grep-regex`, `grep-searcher` and\n `grep-printer` crates together to actually execute the search.\n\nCurrently, there are no plans to make ripgrep core available as an independent\nlibrary. However, much of the heavy lifting of ripgrep is done via its\nconstituent crates, which can be reused independent of ripgrep. Unfortunately,\nthere is no guide or tutorial to teach folks how to do this yet.", "messages": null, "tools": null} {"id": "7695642a4629da5e", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/api/json_pointer/operator_eq.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 3364, "sha256": "1131a249c0f1f2fef2c3bb1a497547374fe415f8b18ddf605023532d8005583f", "text": "# nlohmann::json_pointer::operator==\n\n```cpp\n// until C++20\ntemplate\nbool operator==(\n const json_pointer& lhs,\n const json_pointer& rhs) noexcept; // (1)\n\ntemplate\nbool operator==(\n const json_pointer& lhs,\n const StringType& rhs); // (2)\n\ntemplate\nbool operator==(\n const StringType& lhs,\n const json_pointer& rhs); // (2)\n\n// since C++20\nclass json_pointer {\n template\n bool operator==(\n const json_pointer& rhs) const noexcept; // (1)\n\n bool operator==(const string_t& rhs) const; // (2)\n};\n```\n\n1. Compares two JSON pointers for equality by comparing their reference tokens.\n\n2. Compares a JSON pointer and a string or a string and a JSON pointer for equality by converting the string to a JSON\n pointer and comparing the JSON pointers according to 1.\n\n## Template parameters\n\n`RefStringTypeLhs`, `RefStringTypeRhs`\n: the string type of the left-hand side or right-hand side JSON pointer, respectively\n\n`StringType`\n: the string type derived from the `json_pointer` operand ([`json_pointer::string_t`](string_t.md))\n\n## Parameters\n\n`lhs` (in)\n: first value to consider\n\n`rhs` (in)\n: second value to consider\n\n## Return value\n\nwhether the values `lhs`/`*this` and `rhs` are equal\n\n## Exception safety\n\n1. No-throw guarantee: this function never throws exceptions.\n2. Strong exception safety: if an exception occurs, the original value stays intact.\n\n## Exceptions\n\n1. (none)\n2. The function can throw the following exceptions:\n - Throws [parse_error.107](../../home/exceptions.md#jsonexceptionparse_error107) if the given JSON pointer `s` is\n nonempty and does not begin with a slash (`/`); see example below.\n - Throws [parse_error.108](../../home/exceptions.md#jsonexceptionparse_error108) if a tilde (`~`) in the given JSON\n pointer `s` is not followed by `0` (representing `~`) or `1` (representing `/`); see example below.\n\n## Complexity\n\nConstant if `lhs` and `rhs` differ in the number of reference tokens, otherwise linear in the number of reference\ntokens.\n\n## Notes\n\n!!! warning \"Deprecation\"\n\n Overload 2 is deprecated and will be removed in a future major version release.\n\n## Examples\n\n??? example \"Example: (1) Comparing JSON pointers\"\n\n The example demonstrates comparing JSON pointers.\n \n ```cpp\n --8<-- \"examples/json_pointer__operator__equal.cpp\"\n ```\n \n Output:\n \n ```\n --8<-- \"examples/json_pointer__operator__equal.output\"\n ```\n\n??? example \"Example: (2) Comparing JSON pointers and strings\"\n\n The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception.\n \n ```cpp\n --8<-- \"examples/json_pointer__operator__equal_stringtype.cpp\"\n ```\n \n Output:\n \n ```\n --8<-- \"examples/json_pointer__operator__equal_stringtype.output\"\n ```\n\n## Version history\n\n1. Added in version 2.1.0. Added C++20 member functions in version 3.11.2.\n2. Added for backward compatibility and deprecated in version 3.11.2.", "messages": null, "tools": null} {"id": "76eed34c69243c5f", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/environment-react-ssr/__tests__/environment-react-ssr.spec.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 3742, "sha256": "453d34cd504b6c65fa3910e5337367d93c9494dd24ceb47593d540e8aefb9cd1", "text": "import fs from 'node:fs'\nimport path from 'node:path'\nimport { stripVTControlCharacters } from 'node:util'\nimport { describe, expect, onTestFinished, test } from 'vitest'\nimport {\n isBuild,\n isBundledDev,\n page,\n readDepOptimizationMetadata,\n readFile,\n serverLogs,\n testDir,\n} from '~utils'\n\ntest('basic', async () => {\n await page.getByText('hydrated: true').isVisible()\n await page.getByText('Count: 0').isVisible()\n await page.getByRole('button', { name: '+' }).click()\n await page.getByText('Count: 1').isVisible()\n})\n\ndescribe.runIf(!isBuild)('pre-bundling', () => {\n // bundled dev by design: the client environment has no dep optimizer, so\n // there is no .vite/deps folder to read. Dependencies come from the bundle.\n test.skipIf(isBundledDev)('client', async () => {\n const metaJson = readDepOptimizationMetadata()\n\n expect(metaJson.optimized['react']).toBeTruthy()\n expect(metaJson.optimized['react-dom/client']).toBeTruthy()\n expect(metaJson.optimized['react/jsx-dev-runtime']).toBeTruthy()\n\n expect(metaJson.optimized['react-dom/server']).toBeFalsy()\n })\n\n test('ssr', async () => {\n const metaJson = readDepOptimizationMetadata('ssr')\n\n expect(metaJson.optimized['react']).toBeTruthy()\n expect(metaJson.optimized['react-dom/server']).toBeTruthy()\n expect(metaJson.optimized['react/jsx-dev-runtime']).toBeTruthy()\n\n expect(metaJson.optimized['react-dom/client']).toBeFalsy()\n\n // process.env.NODE_ENV should be kept as keepProcessEnv is true\n const depsFiles = fs\n .readdirSync(path.resolve(testDir, 'node_modules/.vite/deps_ssr'), {\n withFileTypes: true,\n })\n .filter((file) => file.isFile() && file.name.endsWith('.js'))\n .map((file) => path.join(file.parentPath, file.name))\n const depsFilesWithProcessEnvNodeEnv = depsFiles.filter((file) =>\n fs.readFileSync(file, 'utf-8').includes('process.env.NODE_ENV'),\n )\n\n expect(depsFilesWithProcessEnvNodeEnv.length).toBeGreaterThan(0)\n })\n\n // bundled dev by design: there is no client dep-optimizer metadata to\n // compare before and after. The reload this test checks cannot happen.\n test.skipIf(isBundledDev)('deps reload', async () => {\n const envs = ['client', 'server'] as const\n\n const clientMeta = readDepOptimizationMetadata('client')\n const ssrMeta = readDepOptimizationMetadata('ssr')\n expect(clientMeta.optimized['react-fake-client']).toBeFalsy()\n expect(clientMeta.optimized['react-fake-server']).toBeFalsy()\n expect(ssrMeta.optimized['react-fake-server']).toBeFalsy()\n expect(ssrMeta.optimized['react-fake-client']).toBeFalsy()\n\n envs.forEach((env) => {\n const filePath = path.resolve(testDir, `src/entry-${env}.tsx`)\n const originalContent = readFile(filePath)\n fs.writeFileSync(\n filePath,\n `import 'react-fake-${env}'\\n${originalContent}`,\n 'utf-8',\n )\n onTestFinished(() => {\n fs.writeFileSync(filePath, originalContent, 'utf-8')\n })\n })\n\n await expect\n .poll(() =>\n serverLogs\n .map(\n (log) =>\n stripVTControlCharacters(log).match(\n /dependenc(?:y|ies) optimized: (react-fake-.*)/,\n )?.[1],\n )\n .filter(Boolean),\n )\n .toStrictEqual(['react-fake-server', 'react-fake-client'])\n\n const clientMetaNew = readDepOptimizationMetadata('client')\n const ssrMetaNew = readDepOptimizationMetadata('ssr')\n expect(clientMetaNew.optimized['react-fake-client']).toBeTruthy()\n expect(clientMetaNew.optimized['react-fake-server']).toBeFalsy()\n expect(ssrMetaNew.optimized['react-fake-server']).toBeTruthy()\n expect(ssrMetaNew.optimized['react-fake-client']).toBeFalsy()\n })\n})", "messages": null, "tools": null} {"id": "773530ae1aa9606b", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/js-sourcemap/index.html", "lang": "html", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 810, "sha256": "e7f707691c6e8097973d4ce0b9120f28b35e42669aeea401f13a504d8b8865cc", "text": "
\n

JS Sourcemap

\n
dynamic
\n
\n\n\n\n\n\n\n\n\n\n\n\n", "messages": null, "tools": null} {"id": "783b30b373c6478d", "category": "code", "domain": "code", "source": "fmt", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "test/gtest/gmock-gtest-all.cc", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/fmtlib/fmt", "commit": "4f645a8d5d7aa6f8c5ba57e9af0396e4761d3f81", "collector": "tools/harvest.py"}, "chars": 532838, "sha256": "95cfe0dda982a27d4b8cd7a2aa42c33bdfe7bca144d6443ab5f83ea2e1abb710", "text": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// Google C++ Testing and Mocking Framework (Google Test)\n//\n// Sometimes it's desirable to build Google Test by compiling a single file.\n// This file serves this purpose.\n\n// This line ensures that gtest.h can be compiled on its own, even\n// when it's fused.\n#include \"gtest/gtest.h\"\n\n// The following lines pull in the real gtest *.cc files.\n// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// The Google C++ Testing and Mocking Framework (Google Test)\n\n// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// Utilities for testing Google Test itself and code that uses Google Test\n// (e.g. frameworks built on top of Google Test).\n\n// GOOGLETEST_CM0004 DO NOT DELETE\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_\n#define GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_\n\n\nGTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \\\n/* class A needs to have dll-interface to be used by clients of class B */)\n\nnamespace testing {\n\n// This helper class can be used to mock out Google Test failure reporting\n// so that we can test Google Test or code that builds on Google Test.\n//\n// An object of this class appends a TestPartResult object to the\n// TestPartResultArray object given in the constructor whenever a Google Test\n// failure is reported. It can either intercept only failures that are\n// generated in the same thread that created this object or it can intercept\n// all generated failures. The scope of this mock object can be controlled with\n// the second argument to the two arguments constructor.\nclass GTEST_API_ ScopedFakeTestPartResultReporter\n : public TestPartResultReporterInterface {\n public:\n // The two possible mocking modes of this object.\n enum InterceptMode {\n INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.\n INTERCEPT_ALL_THREADS // Intercepts all failures.\n };\n\n // The c'tor sets this object as the test part result reporter used\n // by Google Test. The 'result' parameter specifies where to report the\n // results. This reporter will only catch failures generated in the current\n // thread. DEPRECATED\n explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);\n\n // Same as above, but you can choose the interception scope of this object.\n ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,\n TestPartResultArray* result);\n\n // The d'tor restores the previous test part result reporter.\n ~ScopedFakeTestPartResultReporter() override;\n\n // Appends the TestPartResult object to the TestPartResultArray\n // received in the constructor.\n //\n // This method is from the TestPartResultReporterInterface\n // interface.\n void ReportTestPartResult(const TestPartResult& result) override;\n\n private:\n void Init();\n\n const InterceptMode intercept_mode_;\n TestPartResultReporterInterface* old_reporter_;\n TestPartResultArray* const result_;\n\n GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);\n};\n\nnamespace internal {\n\n// A helper class for implementing EXPECT_FATAL_FAILURE() and\n// EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given\n// TestPartResultArray contains exactly one failure that has the given\n// type and contains the given substring. If that's not the case, a\n// non-fatal failure will be generated.\nclass GTEST_API_ SingleFailureChecker {\n public:\n // The constructor remembers the arguments.\n SingleFailureChecker(const TestPartResultArray* results,\n TestPartResult::Type type, const std::string& substr);\n ~SingleFailureChecker();\n private:\n const TestPartResultArray* const results_;\n const TestPartResult::Type type_;\n const std::string substr_;\n\n GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);\n};\n\n} // namespace internal\n\n} // namespace testing\n\nGTEST_DISABLE_MSC_WARNINGS_POP_() // 4251\n\n// A set of macros for testing Google Test assertions or code that's expected\n// to generate Google Test fatal failures. It verifies that the given\n// statement will cause exactly one fatal Google Test failure with 'substr'\n// being part of the failure message.\n//\n// There are two different versions of this macro. EXPECT_FATAL_FAILURE only\n// affects and considers failures generated in the current thread and\n// EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.\n//\n// The verification of the assertion is done correctly even when the statement\n// throws an exception or aborts the current function.\n//\n// Known restrictions:\n// - 'statement' cannot reference local non-static variables or\n// non-static members of the current object.\n// - 'statement' cannot return a value.\n// - You cannot stream a failure message to this macro.\n//\n// Note that even though the implementations of the following two\n// macros are much alike, we cannot refactor them to use a common\n// helper macro, due to some peculiarity in how the preprocessor\n// works. The AcceptsMacroThatExpandsToUnprotectedComma test in\n// gtest_unittest.cc will fail to compile if we do that.\n#define EXPECT_FATAL_FAILURE(statement, substr) \\\n do { \\\n class GTestExpectFatalFailureHelper {\\\n public:\\\n static void Execute() { statement; }\\\n };\\\n ::testing::TestPartResultArray gtest_failures;\\\n ::testing::internal::SingleFailureChecker gtest_checker(\\\n >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\\\n {\\\n ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\\\n ::testing::ScopedFakeTestPartResultReporter:: \\\n INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\\\n GTestExpectFatalFailureHelper::Execute();\\\n }\\\n } while (::testing::internal::AlwaysFalse())\n\n#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \\\n do { \\\n class GTestExpectFatalFailureHelper {\\\n public:\\\n static void Execute() { statement; }\\\n };\\\n ::testing::TestPartResultArray gtest_failures;\\\n ::testing::internal::SingleFailureChecker gtest_checker(\\\n >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\\\n {\\\n ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\\\n ::testing::ScopedFakeTestPartResultReporter:: \\\n INTERCEPT_ALL_THREADS, >est_failures);\\\n GTestExpectFatalFailureHelper::Execute();\\\n }\\\n } while (::testing::internal::AlwaysFalse())\n\n// A macro for testing Google Test assertions or code that's expected to\n// generate Google Test non-fatal failures. It asserts that the given\n// statement will cause exactly one non-fatal Google Test failure with 'substr'\n// being part of the failure message.\n//\n// There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only\n// affects and considers failures generated in the current thread and\n// EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.\n//\n// 'statement' is allowed to reference local variables and members of\n// the current object.\n//\n// The verification of the assertion is done correctly even when the statement\n// throws an exception or aborts the current function.\n//\n// Known restrictions:\n// - You cannot stream a failure message to this macro.\n//\n// Note that even though the implementations of the following two\n// macros are much alike, we cannot refactor them to use a common\n// helper macro, due to some peculiarity in how the preprocessor\n// works. If we do that, the code won't compile when the user gives\n// EXPECT_NONFATAL_FAILURE() a statement that contains a macro that\n// expands to code containing an unprotected comma. The\n// AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc\n// catches that.\n//\n// For the same reason, we have to write\n// if (::testing::internal::AlwaysTrue()) { statement; }\n// instead of\n// GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)\n// to avoid an MSVC warning on unreachable code.\n#define EXPECT_NONFATAL_FAILURE(statement, substr) \\\n do {\\\n ::testing::TestPartResultArray gtest_failures;\\\n ::testing::internal::SingleFailureChecker gtest_checker(\\\n >est_failures, ::testing::TestPartResult::kNonFatalFailure, \\\n (substr));\\\n {\\\n ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\\\n ::testing::ScopedFakeTestPartResultReporter:: \\\n INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\\\n if (::testing::internal::AlwaysTrue()) { statement; }\\\n }\\\n } while (::testing::internal::AlwaysFalse())\n\n#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \\\n do {\\\n ::testing::TestPartResultArray gtest_failures;\\\n ::testing::internal::SingleFailureChecker gtest_checker(\\\n >est_failures, ::testing::TestPartResult::kNonFatalFailure, \\\n (substr));\\\n {\\\n ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\\\n ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \\\n >est_failures);\\\n if (::testing::internal::AlwaysTrue()) { statement; }\\\n }\\\n } while (::testing::internal::AlwaysFalse())\n\n#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include // NOLINT\n#include \n#include \n#include \n#include \n#include \n#include \n#include // NOLINT\n#include \n#include \n\n#if GTEST_OS_LINUX\n\n# include // NOLINT\n# include // NOLINT\n# include // NOLINT\n// Declares vsnprintf(). This header is not available on Windows.\n# include // NOLINT\n# include // NOLINT\n# include // NOLINT\n# include // NOLINT\n# include \n\n#elif GTEST_OS_ZOS\n# include // NOLINT\n\n// On z/OS we additionally need strings.h for strcasecmp.\n# include // NOLINT\n\n#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.\n\n# include // NOLINT\n# undef min\n\n#elif GTEST_OS_WINDOWS // We are on Windows proper.\n\n# include // NOLINT\n# undef min\n\n#ifdef _MSC_VER\n# include // NOLINT\n#endif\n\n# include // NOLINT\n# include // NOLINT\n# include // NOLINT\n# include // NOLINT\n\n# if GTEST_OS_WINDOWS_MINGW\n# include // NOLINT\n# endif // GTEST_OS_WINDOWS_MINGW\n\n#else\n\n// cpplint thinks that the header is already included, so we want to\n// silence it.\n# include // NOLINT\n# include // NOLINT\n\n#endif // GTEST_OS_LINUX\n\n#if GTEST_HAS_EXCEPTIONS\n# include \n#endif\n\n#if GTEST_CAN_STREAM_RESULTS_\n# include // NOLINT\n# include // NOLINT\n# include // NOLINT\n# include // NOLINT\n#endif\n\n// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Utility functions and classes used by the Google C++ testing framework.//\n// This file contains purely Google Test's internal implementation. Please\n// DO NOT #INCLUDE IT IN A USER PROGRAM.\n\n#ifndef GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_\n#define GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_\n\n#ifndef _WIN32_WCE\n# include \n#endif // !_WIN32_WCE\n#include \n#include // For strtoll/_strtoul64/malloc/free.\n#include // For memmove.\n\n#include \n#include \n#include \n#include \n#include \n\n\n#if GTEST_CAN_STREAM_RESULTS_\n# include // NOLINT\n# include // NOLINT\n#endif\n\n#if GTEST_OS_WINDOWS\n# include // NOLINT\n#endif // GTEST_OS_WINDOWS\n\n\nGTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \\\n/* class A needs to have dll-interface to be used by clients of class B */)\n\nnamespace testing {\n\n// Declares the flags.\n//\n// We don't want the users to modify this flag in the code, but want\n// Google Test's own unit tests to be able to access it. Therefore we\n// declare it here as opposed to in gtest.h.\nGTEST_DECLARE_bool_(death_test_use_fork);\n\nnamespace internal {\n\n// The value of GetTestTypeId() as seen from within the Google Test\n// library. This is solely for testing GetTestTypeId().\nGTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;\n\n// Names of the flags (needed for parsing Google Test flags).\nconst char kAlsoRunDisabledTestsFlag[] = \"also_run_disabled_tests\";\nconst char kBreakOnFailureFlag[] = \"break_on_failure\";\nconst char kCatchExceptionsFlag[] = \"catch_exceptions\";\nconst char kColorFlag[] = \"color\";\nconst char kFailFast[] = \"fail_fast\";\nconst char kFilterFlag[] = \"filter\";\nconst char kListTestsFlag[] = \"list_tests\";\nconst char kOutputFlag[] = \"output\";\nconst char kBriefFlag[] = \"brief\";\nconst char kPrintTimeFlag[] = \"print_time\";\nconst char kPrintUTF8Flag[] = \"print_utf8\";\nconst char kRandomSeedFlag[] = \"random_seed\";\nconst char kRepeatFlag[] = \"repeat\";\nconst char kShuffleFlag[] = \"shuffle\";\nconst char kStackTraceDepthFlag[] = \"stack_trace_depth\";\nconst char kStreamResultToFlag[] = \"stream_result_to\";\nconst char kThrowOnFailureFlag[] = \"throw_on_failure\";\nconst char kFlagfileFlag[] = \"flagfile\";\n\n// A valid random seed must be in [1, kMaxRandomSeed].\nconst int kMaxRandomSeed = 99999;\n\n// g_help_flag is true if and only if the --help flag or an equivalent form\n// is specified on the command line.\nGTEST_API_ extern bool g_help_flag;\n\n// Returns the current time in milliseconds.\nGTEST_API_ TimeInMillis GetTimeInMillis();\n\n// Returns true if and only if Google Test should use colors in the output.\nGTEST_API_ bool ShouldUseColor(bool stdout_is_tty);\n\n// Formats the given time in milliseconds as seconds.\nGTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);\n\n// Converts the given time in milliseconds to a date string in the ISO 8601\n// format, without the timezone information. N.B.: due to the use the\n// non-reentrant localtime() function, this function is not thread safe. Do\n// not use it in any code that can be called from multiple threads.\nGTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);\n\n// Parses a string for an Int32 flag, in the form of \"--flag=value\".\n//\n// On success, stores the value of the flag in *value, and returns\n// true. On failure, returns false without changing *value.\nGTEST_API_ bool ParseInt32Flag(\n const char* str, const char* flag, int32_t* value);\n\n// Returns a random seed in range [1, kMaxRandomSeed] based on the\n// given --gtest_random_seed flag value.\ninline int GetRandomSeedFromFlag(int32_t random_seed_flag) {\n const unsigned int raw_seed = (random_seed_flag == 0) ?\n static_cast(GetTimeInMillis()) :\n static_cast(random_seed_flag);\n\n // Normalizes the actual seed to range [1, kMaxRandomSeed] such that\n // it's easy to type.\n const int normalized_seed =\n static_cast((raw_seed - 1U) %\n static_cast(kMaxRandomSeed)) + 1;\n return normalized_seed;\n}\n\n// Returns the first valid random seed after 'seed'. The behavior is\n// undefined if 'seed' is invalid. The seed after kMaxRandomSeed is\n// considered to be 1.\ninline int GetNextRandomSeed(int seed) {\n GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)\n << \"Invalid random seed \" << seed << \" - must be in [1, \"\n << kMaxRandomSeed << \"].\";\n const int next_seed = seed + 1;\n return (next_seed > kMaxRandomSeed) ? 1 : next_seed;\n}\n\n// This class saves the values of all Google Test flags in its c'tor, and\n// restores them in its d'tor.\nclass GTestFlagSaver {\n public:\n // The c'tor.\n GTestFlagSaver() {\n also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);\n break_on_failure_ = GTEST_FLAG(break_on_failure);\n catch_exceptions_ = GTEST_FLAG(catch_exceptions);\n color_ = GTEST_FLAG(color);\n death_test_style_ = GTEST_FLAG(death_test_style);\n death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);\n fail_fast_ = GTEST_FLAG(fail_fast);\n filter_ = GTEST_FLAG(filter);\n internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);\n list_tests_ = GTEST_FLAG(list_tests);\n output_ = GTEST_FLAG(output);\n brief_ = GTEST_FLAG(brief);\n print_time_ = GTEST_FLAG(print_time);\n print_utf8_ = GTEST_FLAG(print_utf8);\n random_seed_ = GTEST_FLAG(random_seed);\n repeat_ = GTEST_FLAG(repeat);\n shuffle_ = GTEST_FLAG(shuffle);\n stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);\n stream_result_to_ = GTEST_FLAG(stream_result_to);\n throw_on_failure_ = GTEST_FLAG(throw_on_failure);\n }\n\n // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.\n ~GTestFlagSaver() {\n GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;\n GTEST_FLAG(break_on_failure) = break_on_failure_;\n GTEST_FLAG(catch_exceptions) = catch_exceptions_;\n GTEST_FLAG(color) = color_;\n GTEST_FLAG(death_test_style) = death_test_style_;\n GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;\n GTEST_FLAG(filter) = filter_;\n GTEST_FLAG(fail_fast) = fail_fast_;\n GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;\n GTEST_FLAG(list_tests) = list_tests_;\n GTEST_FLAG(output) = output_;\n GTEST_FLAG(brief) = brief_;\n GTEST_FLAG(print_time) = print_time_;\n GTEST_FLAG(print_utf8) = print_utf8_;\n GTEST_FLAG(random_seed) = random_seed_;\n GTEST_FLAG(repeat) = repeat_;\n GTEST_FLAG(shuffle) = shuffle_;\n GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;\n GTEST_FLAG(stream_result_to) = stream_result_to_;\n GTEST_FLAG(throw_on_failure) = throw_on_failure_;\n }\n\n private:\n // Fields for saving the original values of flags.\n bool also_run_disabled_tests_;\n bool break_on_failure_;\n bool catch_exceptions_;\n std::string color_;\n std::string death_test_style_;\n bool death_test_use_fork_;\n bool fail_fast_;\n std::string filter_;\n std::string internal_run_death_test_;\n bool list_tests_;\n std::string output_;\n bool brief_;\n bool print_time_;\n bool print_utf8_;\n int32_t random_seed_;\n int32_t repeat_;\n bool shuffle_;\n int32_t stack_trace_depth_;\n std::string stream_result_to_;\n bool throw_on_failure_;\n} GTEST_ATTRIBUTE_UNUSED_;\n\n// Converts a Unicode code point to a narrow string in UTF-8 encoding.\n// code_point parameter is of type UInt32 because wchar_t may not be\n// wide enough to contain a code point.\n// If the code_point is not a valid Unicode code point\n// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted\n// to \"(Invalid Unicode 0xXXXXXXXX)\".\nGTEST_API_ std::string CodePointToUtf8(uint32_t code_point);\n\n// Converts a wide string to a narrow string in UTF-8 encoding.\n// The wide string is assumed to have the following encoding:\n// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)\n// UTF-32 if sizeof(wchar_t) == 4 (on Linux)\n// Parameter str points to a null-terminated wide string.\n// Parameter num_chars may additionally limit the number\n// of wchar_t characters processed. -1 is used when the entire string\n// should be processed.\n// If the string contains code points that are not valid Unicode code points\n// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output\n// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding\n// and contains invalid UTF-16 surrogate pairs, values in those pairs\n// will be encoded as individual Unicode characters from Basic Normal Plane.\nGTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);\n\n// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file\n// if the variable is present. If a file already exists at this location, this\n// function will write over it. If the variable is present, but the file cannot\n// be created, prints an error and exits.\nvoid WriteToShardStatusFileIfNeeded();\n\n// Checks whether sharding is enabled by examining the relevant\n// environment variable values. If the variables are present,\n// but inconsistent (e.g., shard_index >= total_shards), prints\n// an error and exits. If in_subprocess_for_death_test, sharding is\n// disabled because it must only be applied to the original test\n// process. Otherwise, we could filter out death tests we intended to execute.\nGTEST_API_ bool ShouldShard(const char* total_shards_str,\n const char* shard_index_str,\n bool in_subprocess_for_death_test);\n\n// Parses the environment variable var as a 32-bit integer. If it is unset,\n// returns default_val. If it is not a 32-bit integer, prints an error and\n// and aborts.\nGTEST_API_ int32_t Int32FromEnvOrDie(const char* env_var, int32_t default_val);\n\n// Given the total number of shards, the shard index, and the test id,\n// returns true if and only if the test should be run on this shard. The test id\n// is some arbitrary but unique non-negative integer assigned to each test\n// method. Assumes that 0 <= shard_index < total_shards.\nGTEST_API_ bool ShouldRunTestOnShard(\n int total_shards, int shard_index, int test_id);\n\n// STL container utilities.\n\n// Returns the number of elements in the given container that satisfy\n// the given predicate.\ntemplate \ninline int CountIf(const Container& c, Predicate predicate) {\n // Implemented as an explicit loop since std::count_if() in libCstd on\n // Solaris has a non-standard signature.\n int count = 0;\n for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {\n if (predicate(*it))\n ++count;\n }\n return count;\n}\n\n// Applies a function/functor to each element in the container.\ntemplate \nvoid ForEach(const Container& c, Functor functor) {\n std::for_each(c.begin(), c.end(), functor);\n}\n\n// Returns the i-th element of the vector, or default_value if i is not\n// in range [0, v.size()).\ntemplate \ninline E GetElementOr(const std::vector& v, int i, E default_value) {\n return (i < 0 || i >= static_cast(v.size())) ? default_value\n : v[static_cast(i)];\n}\n\n// Performs an in-place shuffle of a range of the vector's elements.\n// 'begin' and 'end' are element indices as an STL-style range;\n// i.e. [begin, end) are shuffled, where 'end' == size() means to\n// shuffle to the end of the vector.\ntemplate \nvoid ShuffleRange(internal::Random* random, int begin, int end,\n std::vector* v) {\n const int size = static_cast(v->size());\n GTEST_CHECK_(0 <= begin && begin <= size)\n << \"Invalid shuffle range start \" << begin << \": must be in range [0, \"\n << size << \"].\";\n GTEST_CHECK_(begin <= end && end <= size)\n << \"Invalid shuffle range finish \" << end << \": must be in range [\"\n << begin << \", \" << size << \"].\";\n\n // Fisher-Yates shuffle, from\n // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle\n for (int range_width = end - begin; range_width >= 2; range_width--) {\n const int last_in_range = begin + range_width - 1;\n const int selected =\n begin +\n static_cast(random->Generate(static_cast(range_width)));\n std::swap((*v)[static_cast(selected)],\n (*v)[static_cast(last_in_range)]);\n }\n}\n\n// Performs an in-place shuffle of the vector's elements.\ntemplate \ninline void Shuffle(internal::Random* random, std::vector* v) {\n ShuffleRange(random, 0, static_cast(v->size()), v);\n}\n\n// A function for deleting an object. Handy for being used as a\n// functor.\ntemplate \nstatic void Delete(T* x) {\n delete x;\n}\n\n// A predicate that checks the key of a TestProperty against a known key.\n//\n// TestPropertyKeyIs is copyable.\nclass TestPropertyKeyIs {\n public:\n // Constructor.\n //\n // TestPropertyKeyIs has NO default constructor.\n explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}\n\n // Returns true if and only if the test name of test property matches on key_.\n bool operator()(const TestProperty& test_property) const {\n return test_property.key() == key_;\n }\n\n private:\n std::string key_;\n};\n\n// Class UnitTestOptions.\n//\n// This class contains functions for processing options the user\n// specifies when running the tests. It has only static members.\n//\n// In most cases, the user can specify an option using either an\n// environment variable or a command line flag. E.g. you can set the\n// test filter using either GTEST_FILTER or --gtest_filter. If both\n// the variable and the flag are present, the latter overrides the\n// former.\nclass GTEST_API_ UnitTestOptions {\n public:\n // Functions for processing the gtest_output flag.\n\n // Returns the output format, or \"\" for normal printed output.\n static std::string GetOutputFormat();\n\n // Returns the absolute path of the requested output file, or the\n // default (test_detail.xml in the original working directory) if\n // none was explicitly specified.\n static std::string GetAbsolutePathToOutputFile();\n\n // Functions for processing the gtest_filter flag.\n\n // Returns true if and only if the user-specified filter matches the test\n // suite name and the test name.\n static bool FilterMatchesTest(const std::string& test_suite_name,\n const std::string& test_name);\n\n#if GTEST_OS_WINDOWS\n // Function for supporting the gtest_catch_exception flag.\n\n // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the\n // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.\n // This function is useful as an __except condition.\n static int GTestShouldProcessSEH(DWORD exception_code);\n#endif // GTEST_OS_WINDOWS\n\n // Returns true if \"name\" matches the ':' separated list of glob-style\n // filters in \"filter\".\n static bool MatchesFilter(const std::string& name, const char* filter);\n};\n\n// Returns the current application's name, removing directory path if that\n// is present. Used by UnitTestOptions::GetOutputFile.\nGTEST_API_ FilePath GetCurrentExecutableName();\n\n// The role interface for getting the OS stack trace as a string.\nclass OsStackTraceGetterInterface {\n public:\n OsStackTraceGetterInterface() {}\n virtual ~OsStackTraceGetterInterface() {}\n\n // Returns the current OS stack trace as an std::string. Parameters:\n //\n // max_depth - the maximum number of stack frames to be included\n // in the trace.\n // skip_count - the number of top frames to be skipped; doesn't count\n // against max_depth.\n virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0;\n\n // UponLeavingGTest() should be called immediately before Google Test calls\n // user code. It saves some information about the current stack that\n // CurrentStackTrace() will use to find and hide Google Test stack frames.\n virtual void UponLeavingGTest() = 0;\n\n // This string is inserted in place of stack frames that are part of\n // Google Test's implementation.\n static const char* const kElidedFramesMarker;\n\n private:\n GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);\n};\n\n// A working implementation of the OsStackTraceGetterInterface interface.\nclass OsStackTraceGetter : public OsStackTraceGetterInterface {\n public:\n OsStackTraceGetter() {}\n\n std::string CurrentStackTrace(int max_depth, int skip_count) override;\n void UponLeavingGTest() override;\n\n private:\n#if GTEST_HAS_ABSL\n Mutex mutex_; // Protects all internal state.\n\n // We save the stack frame below the frame that calls user code.\n // We do this because the address of the frame immediately below\n // the user code changes between the call to UponLeavingGTest()\n // and any calls to the stack trace code from within the user code.\n void* caller_frame_ = nullptr;\n#endif // GTEST_HAS_ABSL\n\n GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);\n};\n\n// Information about a Google Test trace point.\nstruct TraceInfo {\n const char* file;\n int line;\n std::string message;\n};\n\n// This is the default global test part result reporter used in UnitTestImpl.\n// This class should only be used by UnitTestImpl.\nclass DefaultGlobalTestPartResultReporter\n : public TestPartResultReporterInterface {\n public:\n explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);\n // Implements the TestPartResultReporterInterface. Reports the test part\n // result in the current test.\n void ReportTestPartResult(const TestPartResult& result) override;\n\n private:\n UnitTestImpl* const unit_test_;\n\n GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);\n};\n\n// This is the default per thread test part result reporter used in\n// UnitTestImpl. This class should only be used by UnitTestImpl.\nclass DefaultPerThreadTestPartResultReporter\n : public TestPartResultReporterInterface {\n public:\n explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);\n // Implements the TestPartResultReporterInterface. The implementation just\n // delegates to the current global test part result reporter of *unit_test_.\n void ReportTestPartResult(const TestPartResult& result) override;\n\n private:\n UnitTestImpl* const unit_test_;\n\n GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);\n};\n\n// The private implementation of the UnitTest class. We don't protect\n// the methods under a mutex, as this class is not accessible by a\n// user and the UnitTest class that delegates work to this class does\n// proper locking.\nclass GTEST_API_ UnitTestImpl {\n public:\n explicit UnitTestImpl(UnitTest* parent);\n virtual ~UnitTestImpl();\n\n // There are two different ways to register your own TestPartResultReporter.\n // You can register your own repoter to listen either only for test results\n // from the current thread or for results from all threads.\n // By default, each per-thread test result repoter just passes a new\n // TestPartResult to the global test result reporter, which registers the\n // test part result for the currently running test.\n\n // Returns the global test part result reporter.\n TestPartResultReporterInterface* GetGlobalTestPartResultReporter();\n\n // Sets the global test part result reporter.\n void SetGlobalTestPartResultReporter(\n TestPartResultReporterInterface* reporter);\n\n // Returns the test part result reporter for the current thread.\n TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();\n\n // Sets the test part result reporter for the current thread.\n void SetTestPartResultReporterForCurrentThread(\n TestPartResultReporterInterface* reporter);\n\n // Gets the number of successful test suites.\n int successful_test_suite_count() const;\n\n // Gets the number of failed test suites.\n int failed_test_suite_count() const;\n\n // Gets the number of all test suites.\n int total_test_suite_count() const;\n\n // Gets the number of all test suites that contain at least one test\n // that should run.\n int test_suite_to_run_count() const;\n\n // Gets the number of successful tests.\n int successful_test_count() const;\n\n // Gets the number of skipped tests.\n int skipped_test_count() const;\n\n // Gets the number of failed tests.\n int failed_test_count() const;\n\n // Gets the number of disabled tests that will be reported in the XML report.\n int reportable_disabled_test_count() const;\n\n // Gets the number of disabled tests.\n int disabled_test_count() const;\n\n // Gets the number of tests to be printed in the XML report.\n int reportable_test_count() const;\n\n // Gets the number of all tests.\n int total_test_count() const;\n\n // Gets the number of tests that should run.\n int test_to_run_count() const;\n\n // Gets the time of the test program start, in ms from the start of the\n // UNIX epoch.\n TimeInMillis start_timestamp() const { return start_timestamp_; }\n\n // Gets the elapsed time, in milliseconds.\n TimeInMillis elapsed_time() const { return elapsed_time_; }\n\n // Returns true if and only if the unit test passed (i.e. all test suites\n // passed).\n bool Passed() const { return !Failed(); }\n\n // Returns true if and only if the unit test failed (i.e. some test suite\n // failed or something outside of all tests failed).\n bool Failed() const {\n return failed_test_suite_count() > 0 || ad_hoc_test_result()->Failed();\n }\n\n // Gets the i-th test suite among all the test suites. i can range from 0 to\n // total_test_suite_count() - 1. If i is not in that range, returns NULL.\n const TestSuite* GetTestSuite(int i) const {\n const int index = GetElementOr(test_suite_indices_, i, -1);\n return index < 0 ? nullptr : test_suites_[static_cast(i)];\n }\n\n // Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n const TestCase* GetTestCase(int i) const { return GetTestSuite(i); }\n#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n // Gets the i-th test suite among all the test suites. i can range from 0 to\n // total_test_suite_count() - 1. If i is not in that range, returns NULL.\n TestSuite* GetMutableSuiteCase(int i) {\n const int index = GetElementOr(test_suite_indices_, i, -1);\n return index < 0 ? nullptr : test_suites_[static_cast(index)];\n }\n\n // Provides access to the event listener list.\n TestEventListeners* listeners() { return &listeners_; }\n\n // Returns the TestResult for the test that's currently running, or\n // the TestResult for the ad hoc test if no test is running.\n TestResult* current_test_result();\n\n // Returns the TestResult for the ad hoc test.\n const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }\n\n // Sets the OS stack trace getter.\n //\n // Does nothing if the input and the current OS stack trace getter\n // are the same; otherwise, deletes the old getter and makes the\n // input the current getter.\n void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);\n\n // Returns the current OS stack trace getter if it is not NULL;\n // otherwise, creates an OsStackTraceGetter, makes it the current\n // getter, and returns it.\n OsStackTraceGetterInterface* os_stack_trace_getter();\n\n // Returns the current OS stack trace as an std::string.\n //\n // The maximum number of stack frames to be included is specified by\n // the gtest_stack_trace_depth flag. The skip_count parameter\n // specifies the number of top frames to be skipped, which doesn't\n // count against the number of frames to be included.\n //\n // For example, if Foo() calls Bar(), which in turn calls\n // CurrentOsStackTraceExceptTop(1), Foo() will be included in the\n // trace but Bar() and CurrentOsStackTraceExceptTop() won't.\n std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;\n\n // Finds and returns a TestSuite with the given name. If one doesn't\n // exist, creates one and returns it.\n //\n // Arguments:\n //\n // test_suite_name: name of the test suite\n // type_param: the name of the test's type parameter, or NULL if\n // this is not a typed or a type-parameterized test.\n // set_up_tc: pointer to the function that sets up the test suite\n // tear_down_tc: pointer to the function that tears down the test suite\n TestSuite* GetTestSuite(const char* test_suite_name, const char* type_param,\n internal::SetUpTestSuiteFunc set_up_tc,\n internal::TearDownTestSuiteFunc tear_down_tc);\n\n// Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n TestCase* GetTestCase(const char* test_case_name, const char* type_param,\n internal::SetUpTestSuiteFunc set_up_tc,\n internal::TearDownTestSuiteFunc tear_down_tc) {\n return GetTestSuite(test_case_name, type_param, set_up_tc, tear_down_tc);\n }\n#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n // Adds a TestInfo to the unit test.\n //\n // Arguments:\n //\n // set_up_tc: pointer to the function that sets up the test suite\n // tear_down_tc: pointer to the function that tears down the test suite\n // test_info: the TestInfo object\n void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,\n internal::TearDownTestSuiteFunc tear_down_tc,\n TestInfo* test_info) {\n#if GTEST_HAS_DEATH_TEST\n // In order to support thread-safe death tests, we need to\n // remember the original working directory when the test program\n // was first invoked. We cannot do this in RUN_ALL_TESTS(), as\n // the user may have changed the current directory before calling\n // RUN_ALL_TESTS(). Therefore we capture the current directory in\n // AddTestInfo(), which is called to register a TEST or TEST_F\n // before main() is reached.\n if (original_working_dir_.IsEmpty()) {\n original_working_dir_.Set(FilePath::GetCurrentDir());\n GTEST_CHECK_(!original_working_dir_.IsEmpty())\n << \"Failed to get the current working directory.\";\n }\n#endif // GTEST_HAS_DEATH_TEST\n\n GetTestSuite(test_info->test_suite_name(), test_info->type_param(),\n set_up_tc, tear_down_tc)\n ->AddTestInfo(test_info);\n }\n\n // Returns ParameterizedTestSuiteRegistry object used to keep track of\n // value-parameterized tests and instantiate and register them.\n internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() {\n return parameterized_test_registry_;\n }\n\n std::set* ignored_parameterized_test_suites() {\n return &ignored_parameterized_test_suites_;\n }\n\n // Returns TypeParameterizedTestSuiteRegistry object used to keep track of\n // type-parameterized tests and instantiations of them.\n internal::TypeParameterizedTestSuiteRegistry&\n type_parameterized_test_registry() {\n return type_parameterized_test_registry_;\n }\n\n // Sets the TestSuite object for the test that's currently running.\n void set_current_test_suite(TestSuite* a_current_test_suite) {\n current_test_suite_ = a_current_test_suite;\n }\n\n // Sets the TestInfo object for the test that's currently running. If\n // current_test_info is NULL, the assertion results will be stored in\n // ad_hoc_test_result_.\n void set_current_test_info(TestInfo* a_current_test_info) {\n current_test_info_ = a_current_test_info;\n }\n\n // Registers all parameterized tests defined using TEST_P and\n // INSTANTIATE_TEST_SUITE_P, creating regular tests for each test/parameter\n // combination. This method can be called more then once; it has guards\n // protecting from registering the tests more then once. If\n // value-parameterized tests are disabled, RegisterParameterizedTests is\n // present but does nothing.\n void RegisterParameterizedTests();\n\n // Runs all tests in this UnitTest object, prints the result, and\n // returns true if all tests are successful. If any exception is\n // thrown during a test, this test is considered to be failed, but\n // the rest of the tests will still be run.\n bool RunAllTests();\n\n // Clears the results of all tests, except the ad hoc tests.\n void ClearNonAdHocTestResult() {\n ForEach(test_suites_, TestSuite::ClearTestSuiteResult);\n }\n\n // Clears the results of ad-hoc test assertions.\n void ClearAdHocTestResult() {\n ad_hoc_test_result_.Clear();\n }\n\n // Adds a TestProperty to the current TestResult object when invoked in a\n // context of a test or a test suite, or to the global property set. If the\n // result already contains a property with the same key, the value will be\n // updated.\n void RecordProperty(const TestProperty& test_property);\n\n enum ReactionToSharding {\n HONOR_SHARDING_PROTOCOL,\n IGNORE_SHARDING_PROTOCOL\n };\n\n // Matches the full name of each test against the user-specified\n // filter to decide whether the test should run, then records the\n // result in each TestSuite and TestInfo object.\n // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests\n // based on sharding variables in the environment.\n // Returns the number of tests that should run.\n int FilterTests(ReactionToSharding shard_tests);\n\n // Prints the names of the tests matching the user-specified filter flag.\n void ListTestsMatchingFilter();\n\n const TestSuite* current_test_suite() const { return current_test_suite_; }\n TestInfo* current_test_info() { return current_test_info_; }\n const TestInfo* current_test_info() const { return current_test_info_; }\n\n // Returns the vector of environments that need to be set-up/torn-down\n // before/after the tests are run.\n std::vector& environments() { return environments_; }\n\n // Getters for the per-thread Google Test trace stack.\n std::vector& gtest_trace_stack() {\n return *(gtest_trace_stack_.pointer());\n }\n const std::vector& gtest_trace_stack() const {\n return gtest_trace_stack_.get();\n }\n\n#if GTEST_HAS_DEATH_TEST\n void InitDeathTestSubprocessControlInfo() {\n internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());\n }\n // Returns a pointer to the parsed --gtest_internal_run_death_test\n // flag, or NULL if that flag was not specified.\n // This information is useful only in a death test child process.\n // Must not be called before a call to InitGoogleTest.\n const InternalRunDeathTestFlag* internal_run_death_test_flag() const {\n return internal_run_death_test_flag_.get();\n }\n\n // Returns a pointer to the current death test factory.\n internal::DeathTestFactory* death_test_factory() {\n return death_test_factory_.get();\n }\n\n void SuppressTestEventsIfInSubprocess();\n\n friend class ReplaceDeathTestFactory;\n#endif // GTEST_HAS_DEATH_TEST\n\n // Initializes the event listener performing XML output as specified by\n // UnitTestOptions. Must not be called before InitGoogleTest.\n void ConfigureXmlOutput();\n\n#if GTEST_CAN_STREAM_RESULTS_\n // Initializes the event listener for streaming test results to a socket.\n // Must not be called before InitGoogleTest.\n void ConfigureStreamingOutput();\n#endif\n\n // Performs initialization dependent upon flag values obtained in\n // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to\n // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest\n // this function is also called from RunAllTests. Since this function can be\n // called more than once, it has to be idempotent.\n void PostFlagParsingInit();\n\n // Gets the random seed used at the start of the current test iteration.\n int random_seed() const { return random_seed_; }\n\n // Gets the random number generator.\n internal::Random* random() { return &random_; }\n\n // Shuffles all test suites, and the tests within each test suite,\n // making sure that death tests are still run first.\n void ShuffleTests();\n\n // Restores the test suites and tests to their order before the first shuffle.\n void UnshuffleTests();\n\n // Returns the value of GTEST_FLAG(catch_exceptions) at the moment\n // UnitTest::Run() starts.\n bool catch_exceptions() const { return catch_exceptions_; }\n\n private:\n friend class ::testing::UnitTest;\n\n // Used by UnitTest::Run() to capture the state of\n // GTEST_FLAG(catch_exceptions) at the moment it starts.\n void set_catch_exceptions(bool value) { catch_exceptions_ = value; }\n\n // The UnitTest object that owns this implementation object.\n UnitTest* const parent_;\n\n // The working directory when the first TEST() or TEST_F() was\n // executed.\n internal::FilePath original_working_dir_;\n\n // The default test part result reporters.\n DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;\n DefaultPerThreadTestPartResultReporter\n default_per_thread_test_part_result_reporter_;\n\n // Points to (but doesn't own) the global test part result reporter.\n TestPartResultReporterInterface* global_test_part_result_repoter_;\n\n // Protects read and write access to global_test_part_result_reporter_.\n internal::Mutex global_test_part_result_reporter_mutex_;\n\n // Points to (but doesn't own) the per-thread test part result reporter.\n internal::ThreadLocal\n per_thread_test_part_result_reporter_;\n\n // The vector of environments that need to be set-up/torn-down\n // before/after the tests are run.\n std::vector environments_;\n\n // The vector of TestSuites in their original order. It owns the\n // elements in the vector.\n std::vector test_suites_;\n\n // Provides a level of indirection for the test suite list to allow\n // easy shuffling and restoring the test suite order. The i-th\n // element of this vector is the index of the i-th test suite in the\n // shuffled order.\n std::vector test_suite_indices_;\n\n // ParameterizedTestRegistry object used to register value-parameterized\n // tests.\n internal::ParameterizedTestSuiteRegistry parameterized_test_registry_;\n internal::TypeParameterizedTestSuiteRegistry\n type_parameterized_test_registry_;\n\n // The set holding the name of parameterized\n // test suites that may go uninstantiated.\n std::set ignored_parameterized_test_suites_;\n\n // Indicates whether RegisterParameterizedTests() has been called already.\n bool parameterized_tests_registered_;\n\n // Index of the last death test suite registered. Initially -1.\n int last_death_test_suite_;\n\n // This points to the TestSuite for the currently running test. It\n // changes as Google Test goes through one test suite after another.\n // When no test is running, this is set to NULL and Google Test\n // stores assertion results in ad_hoc_test_result_. Initially NULL.\n TestSuite* current_test_suite_;\n\n // This points to the TestInfo for the currently running test. It\n // changes as Google Test goes through one test after another. When\n // no test is running, this is set to NULL and Google Test stores\n // assertion results in ad_hoc_test_result_. Initially NULL.\n TestInfo* current_test_info_;\n\n // Normally, a user only writes assertions inside a TEST or TEST_F,\n // or inside a function called by a TEST or TEST_F. Since Google\n // Test keeps track of which test is current running, it can\n // associate such an assertion with the test it belongs to.\n //\n // If an assertion is encountered when no TEST or TEST_F is running,\n // Google Test attributes the assertion result to an imaginary \"ad hoc\"\n // test, and records the result in ad_hoc_test_result_.\n TestResult ad_hoc_test_result_;\n\n // The list of event listeners that can be used to track events inside\n // Google Test.\n TestEventListeners listeners_;\n\n // The OS stack trace getter. Will be deleted when the UnitTest\n // object is destructed. By default, an OsStackTraceGetter is used,\n // but the user can set this field to use a custom getter if that is\n // desired.\n OsStackTraceGetterInterface* os_stack_trace_getter_;\n\n // True if and only if PostFlagParsingInit() has been called.\n bool post_flag_parse_init_performed_;\n\n // The random number seed used at the beginning of the test run.\n int random_seed_;\n\n // Our random number generator.\n internal::Random random_;\n\n // The time of the test program start, in ms from the start of the\n // UNIX epoch.\n TimeInMillis start_timestamp_;\n\n // How long the test took to run, in milliseconds.\n TimeInMillis elapsed_time_;\n\n#if GTEST_HAS_DEATH_TEST\n // The decomposed components of the gtest_internal_run_death_test flag,\n // parsed when RUN_ALL_TESTS is called.\n std::unique_ptr internal_run_death_test_flag_;\n std::unique_ptr death_test_factory_;\n#endif // GTEST_HAS_DEATH_TEST\n\n // A per-thread stack of traces created by the SCOPED_TRACE() macro.\n internal::ThreadLocal > gtest_trace_stack_;\n\n // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()\n // starts.\n bool catch_exceptions_;\n\n GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);\n}; // class UnitTestImpl\n\n// Convenience function for accessing the global UnitTest\n// implementation object.\ninline UnitTestImpl* GetUnitTestImpl() {\n return UnitTest::GetInstance()->impl();\n}\n\n#if GTEST_USES_SIMPLE_RE\n\n// Internal helper functions for implementing the simple regular\n// expression matcher.\nGTEST_API_ bool IsInSet(char ch, const char* str);\nGTEST_API_ bool IsAsciiDigit(char ch);\nGTEST_API_ bool IsAsciiPunct(char ch);\nGTEST_API_ bool IsRepeat(char ch);\nGTEST_API_ bool IsAsciiWhiteSpace(char ch);\nGTEST_API_ bool IsAsciiWordChar(char ch);\nGTEST_API_ bool IsValidEscape(char ch);\nGTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);\nGTEST_API_ bool ValidateRegex(const char* regex);\nGTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);\nGTEST_API_ bool MatchRepetitionAndRegexAtHead(\n bool escaped, char ch, char repeat, const char* regex, const char* str);\nGTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);\n\n#endif // GTEST_USES_SIMPLE_RE\n\n// Parses the command line for Google Test flags, without initializing\n// other parts of Google Test.\nGTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);\nGTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);\n\n#if GTEST_HAS_DEATH_TEST\n\n// Returns the message describing the last system error, regardless of the\n// platform.\nGTEST_API_ std::string GetLastErrnoDescription();\n\n// Attempts to parse a string into a positive integer pointed to by the\n// number parameter. Returns true if that is possible.\n// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use\n// it here.\ntemplate \nbool ParseNaturalNumber(const ::std::string& str, Integer* number) {\n // Fail fast if the given string does not begin with a digit;\n // this bypasses strtoXXX's \"optional leading whitespace and plus\n // or minus sign\" semantics, which are undesirable here.\n if (str.empty() || !IsDigit(str[0])) {\n return false;\n }\n errno = 0;\n\n char* end;\n // BiggestConvertible is the largest integer type that system-provided\n // string-to-number conversion routines can return.\n using BiggestConvertible = unsigned long long; // NOLINT\n\n const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); // NOLINT\n const bool parse_success = *end == '\\0' && errno == 0;\n\n GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));\n\n const Integer result = static_cast(parsed);\n if (parse_success && static_cast(result) == parsed) {\n *number = result;\n return true;\n }\n return false;\n}\n#endif // GTEST_HAS_DEATH_TEST\n\n// TestResult contains some private methods that should be hidden from\n// Google Test user but are required for testing. This class allow our tests\n// to access them.\n//\n// This class is supplied only for the purpose of testing Google Test's own\n// constructs. Do not use it in user tests, either directly or indirectly.\nclass TestResultAccessor {\n public:\n static void RecordProperty(TestResult* test_result,\n const std::string& xml_element,\n const TestProperty& property) {\n test_result->RecordProperty(xml_element, property);\n }\n\n static void ClearTestPartResults(TestResult* test_result) {\n test_result->ClearTestPartResults();\n }\n\n static const std::vector& test_part_results(\n const TestResult& test_result) {\n return test_result.test_part_results();\n }\n};\n\n#if GTEST_CAN_STREAM_RESULTS_\n\n// Streams test results to the given port on the given host machine.\nclass StreamingListener : public EmptyTestEventListener {\n public:\n // Abstract base class for writing strings to a socket.\n class AbstractSocketWriter {\n public:\n virtual ~AbstractSocketWriter() {}\n\n // Sends a string to the socket.\n virtual void Send(const std::string& message) = 0;\n\n // Closes the socket.\n virtual void CloseConnection() {}\n\n // Sends a string and a newline to the socket.\n void SendLn(const std::string& message) { Send(message + \"\\n\"); }\n };\n\n // Concrete class for actually writing strings to a socket.\n class SocketWriter : public AbstractSocketWriter {\n public:\n SocketWriter(const std::string& host, const std::string& port)\n : sockfd_(-1), host_name_(host), port_num_(port) {\n MakeConnection();\n }\n\n ~SocketWriter() override {\n if (sockfd_ != -1)\n CloseConnection();\n }\n\n // Sends a string to the socket.\n void Send(const std::string& message) override {\n GTEST_CHECK_(sockfd_ != -1)\n << \"Send() can be called only when there is a connection.\";\n\n const auto len = static_cast(message.length());\n if (write(sockfd_, message.c_str(), len) != static_cast(len)) {\n GTEST_LOG_(WARNING)\n << \"stream_result_to: failed to stream to \"\n << host_name_ << \":\" << port_num_;\n }\n }\n\n private:\n // Creates a client socket and connects to the server.\n void MakeConnection();\n\n // Closes the socket.\n void CloseConnection() override {\n GTEST_CHECK_(sockfd_ != -1)\n << \"CloseConnection() can be called only when there is a connection.\";\n\n close(sockfd_);\n sockfd_ = -1;\n }\n\n int sockfd_; // socket file descriptor\n const std::string host_name_;\n const std::string port_num_;\n\n GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);\n }; // class SocketWriter\n\n // Escapes '=', '&', '%', and '\\n' characters in str as \"%xx\".\n static std::string UrlEncode(const char* str);\n\n StreamingListener(const std::string& host, const std::string& port)\n : socket_writer_(new SocketWriter(host, port)) {\n Start();\n }\n\n explicit StreamingListener(AbstractSocketWriter* socket_writer)\n : socket_writer_(socket_writer) { Start(); }\n\n void OnTestProgramStart(const UnitTest& /* unit_test */) override {\n SendLn(\"event=TestProgramStart\");\n }\n\n void OnTestProgramEnd(const UnitTest& unit_test) override {\n // Note that Google Test current only report elapsed time for each\n // test iteration, not for the entire test program.\n SendLn(\"event=TestProgramEnd&passed=\" + FormatBool(unit_test.Passed()));\n\n // Notify the streaming server to stop.\n socket_writer_->CloseConnection();\n }\n\n void OnTestIterationStart(const UnitTest& /* unit_test */,\n int iteration) override {\n SendLn(\"event=TestIterationStart&iteration=\" +\n StreamableToString(iteration));\n }\n\n void OnTestIterationEnd(const UnitTest& unit_test,\n int /* iteration */) override {\n SendLn(\"event=TestIterationEnd&passed=\" +\n FormatBool(unit_test.Passed()) + \"&elapsed_time=\" +\n StreamableToString(unit_test.elapsed_time()) + \"ms\");\n }\n\n // Note that \"event=TestCaseStart\" is a wire format and has to remain\n // \"case\" for compatibility\n void OnTestCaseStart(const TestCase& test_case) override {\n SendLn(std::string(\"event=TestCaseStart&name=\") + test_case.name());\n }\n\n // Note that \"event=TestCaseEnd\" is a wire format and has to remain\n // \"case\" for compatibility\n void OnTestCaseEnd(const TestCase& test_case) override {\n SendLn(\"event=TestCaseEnd&passed=\" + FormatBool(test_case.Passed()) +\n \"&elapsed_time=\" + StreamableToString(test_case.elapsed_time()) +\n \"ms\");\n }\n\n void OnTestStart(const TestInfo& test_info) override {\n SendLn(std::string(\"event=TestStart&name=\") + test_info.name());\n }\n\n void OnTestEnd(const TestInfo& test_info) override {\n SendLn(\"event=TestEnd&passed=\" +\n FormatBool((test_info.result())->Passed()) +\n \"&elapsed_time=\" +\n StreamableToString((test_info.result())->elapsed_time()) + \"ms\");\n }\n\n void OnTestPartResult(const TestPartResult& test_part_result) override {\n const char* file_name = test_part_result.file_name();\n if (file_name == nullptr) file_name = \"\";\n SendLn(\"event=TestPartResult&file=\" + UrlEncode(file_name) +\n \"&line=\" + StreamableToString(test_part_result.line_number()) +\n \"&message=\" + UrlEncode(test_part_result.message()));\n }\n\n private:\n // Sends the given message and a newline to the socket.\n void SendLn(const std::string& message) { socket_writer_->SendLn(message); }\n\n // Called at the start of streaming to notify the receiver what\n // protocol we are using.\n void Start() { SendLn(\"gtest_streaming_protocol_version=1.0\"); }\n\n std::string FormatBool(bool value) { return value ? \"1\" : \"0\"; }\n\n const std::unique_ptr socket_writer_;\n\n GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);\n}; // class StreamingListener\n\n#endif // GTEST_CAN_STREAM_RESULTS_\n\n} // namespace internal\n} // namespace testing\n\nGTEST_DISABLE_MSC_WARNINGS_POP_() // 4251\n\n#endif // GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_\n\n#if GTEST_OS_WINDOWS\n# define vsnprintf _vsnprintf\n#endif // GTEST_OS_WINDOWS\n\n#if GTEST_OS_MAC\n#ifndef GTEST_OS_IOS\n#include \n#endif\n#endif\n\n#if GTEST_HAS_ABSL\n#include \"absl/debugging/failure_signal_handler.h\"\n#include \"absl/debugging/stacktrace.h\"\n#include \"absl/debugging/symbolize.h\"\n#include \"absl/strings/str_cat.h\"\n#endif // GTEST_HAS_ABSL\n\nnamespace testing {\n\nusing internal::CountIf;\nusing internal::ForEach;\nusing internal::GetElementOr;\nusing internal::Shuffle;\n\n// Constants.\n\n// A test whose test suite name or test name matches this filter is\n// disabled and not run.\nstatic const char kDisableTestFilter[] = \"DISABLED_*:*/DISABLED_*\";\n\n// A test suite whose name matches this filter is considered a death\n// test suite and will be run before test suites whose name doesn't\n// match this filter.\nstatic const char kDeathTestSuiteFilter[] = \"*DeathTest:*DeathTest/*\";\n\n// A test filter that matches everything.\nstatic const char kUniversalFilter[] = \"*\";\n\n// The default output format.\nstatic const char kDefaultOutputFormat[] = \"xml\";\n// The default output file.\nstatic const char kDefaultOutputFile[] = \"test_detail\";\n\n// The environment variable name for the test shard index.\nstatic const char kTestShardIndex[] = \"GTEST_SHARD_INDEX\";\n// The environment variable name for the total number of test shards.\nstatic const char kTestTotalShards[] = \"GTEST_TOTAL_SHARDS\";\n// The environment variable name for the test shard status file.\nstatic const char kTestShardStatusFile[] = \"GTEST_SHARD_STATUS_FILE\";\n\nnamespace internal {\n\n// The text used in failure messages to indicate the start of the\n// stack trace.\nconst char kStackTraceMarker[] = \"\\nStack trace:\\n\";\n\n// g_help_flag is true if and only if the --help flag or an equivalent form\n// is specified on the command line.\nbool g_help_flag = false;\n\n// Utilty function to Open File for Writing\nstatic FILE* OpenFileForWriting(const std::string& output_file) {\n FILE* fileout = nullptr;\n FilePath output_file_path(output_file);\n FilePath output_dir(output_file_path.RemoveFileName());\n\n if (output_dir.CreateDirectoriesRecursively()) {\n fileout = posix::FOpen(output_file.c_str(), \"w\");\n }\n if (fileout == nullptr) {\n GTEST_LOG_(FATAL) << \"Unable to open file \\\"\" << output_file << \"\\\"\";\n }\n return fileout;\n}\n\n} // namespace internal\n\n// Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY\n// environment variable.\nstatic const char* GetDefaultFilter() {\n const char* const testbridge_test_only =\n internal::posix::GetEnv(\"TESTBRIDGE_TEST_ONLY\");\n if (testbridge_test_only != nullptr) {\n return testbridge_test_only;\n }\n return kUniversalFilter;\n}\n\n// Bazel passes in the argument to '--test_runner_fail_fast' via the\n// TESTBRIDGE_TEST_RUNNER_FAIL_FAST environment variable.\nstatic bool GetDefaultFailFast() {\n const char* const testbridge_test_runner_fail_fast =\n internal::posix::GetEnv(\"TESTBRIDGE_TEST_RUNNER_FAIL_FAST\");\n if (testbridge_test_runner_fail_fast != nullptr) {\n return strcmp(testbridge_test_runner_fail_fast, \"1\") == 0;\n }\n return false;\n}\n\nGTEST_DEFINE_bool_(\n fail_fast, internal::BoolFromGTestEnv(\"fail_fast\", GetDefaultFailFast()),\n \"True if and only if a test failure should stop further test execution.\");\n\nGTEST_DEFINE_bool_(\n also_run_disabled_tests,\n internal::BoolFromGTestEnv(\"also_run_disabled_tests\", false),\n \"Run disabled tests too, in addition to the tests normally being run.\");\n\nGTEST_DEFINE_bool_(\n break_on_failure, internal::BoolFromGTestEnv(\"break_on_failure\", false),\n \"True if and only if a failed assertion should be a debugger \"\n \"break-point.\");\n\nGTEST_DEFINE_bool_(catch_exceptions,\n internal::BoolFromGTestEnv(\"catch_exceptions\", true),\n \"True if and only if \" GTEST_NAME_\n \" should catch exceptions and treat them as test failures.\");\n\nGTEST_DEFINE_string_(\n color,\n internal::StringFromGTestEnv(\"color\", \"auto\"),\n \"Whether to use colors in the output. Valid values: yes, no, \"\n \"and auto. 'auto' means to use colors if the output is \"\n \"being sent to a terminal and the TERM environment variable \"\n \"is set to a terminal type that supports colors.\");\n\nGTEST_DEFINE_string_(\n filter,\n internal::StringFromGTestEnv(\"filter\", GetDefaultFilter()),\n \"A colon-separated list of glob (not regex) patterns \"\n \"for filtering the tests to run, optionally followed by a \"\n \"'-' and a : separated list of negative patterns (tests to \"\n \"exclude). A test is run if it matches one of the positive \"\n \"patterns and does not match any of the negative patterns.\");\n\nGTEST_DEFINE_bool_(\n install_failure_signal_handler,\n internal::BoolFromGTestEnv(\"install_failure_signal_handler\", false),\n \"If true and supported on the current platform, \" GTEST_NAME_ \" should \"\n \"install a signal handler that dumps debugging information when fatal \"\n \"signals are raised.\");\n\nGTEST_DEFINE_bool_(list_tests, false,\n \"List all tests without running them.\");\n\n// The net priority order after flag processing is thus:\n// --gtest_output command line flag\n// GTEST_OUTPUT environment variable\n// XML_OUTPUT_FILE environment variable\n// ''\nGTEST_DEFINE_string_(\n output,\n internal::StringFromGTestEnv(\"output\",\n internal::OutputFlagAlsoCheckEnvVar().c_str()),\n \"A format (defaults to \\\"xml\\\" but can be specified to be \\\"json\\\"), \"\n \"optionally followed by a colon and an output file name or directory. \"\n \"A directory is indicated by a trailing pathname separator. \"\n \"Examples: \\\"xml:filename.xml\\\", \\\"xml::directoryname/\\\". \"\n \"If a directory is specified, output files will be created \"\n \"within that directory, with file-names based on the test \"\n \"executable's name and, if necessary, made unique by adding \"\n \"digits.\");\n\nGTEST_DEFINE_bool_(\n brief, internal::BoolFromGTestEnv(\"brief\", false),\n \"True if only test failures should be displayed in text output.\");\n\nGTEST_DEFINE_bool_(print_time, internal::BoolFromGTestEnv(\"print_time\", true),\n \"True if and only if \" GTEST_NAME_\n \" should display elapsed time in text output.\");\n\nGTEST_DEFINE_bool_(print_utf8, internal::BoolFromGTestEnv(\"print_utf8\", true),\n \"True if and only if \" GTEST_NAME_\n \" prints UTF8 characters as text.\");\n\nGTEST_DEFINE_int32_(\n random_seed,\n internal::Int32FromGTestEnv(\"random_seed\", 0),\n \"Random number seed to use when shuffling test orders. Must be in range \"\n \"[1, 99999], or 0 to use a seed based on the current time.\");\n\nGTEST_DEFINE_int32_(\n repeat,\n internal::Int32FromGTestEnv(\"repeat\", 1),\n \"How many times to repeat each test. Specify a negative number \"\n \"for repeating forever. Useful for shaking out flaky tests.\");\n\nGTEST_DEFINE_bool_(show_internal_stack_frames, false,\n \"True if and only if \" GTEST_NAME_\n \" should include internal stack frames when \"\n \"printing test failure stack traces.\");\n\nGTEST_DEFINE_bool_(shuffle, internal::BoolFromGTestEnv(\"shuffle\", false),\n \"True if and only if \" GTEST_NAME_\n \" should randomize tests' order on every run.\");\n\nGTEST_DEFINE_int32_(\n stack_trace_depth,\n internal::Int32FromGTestEnv(\"stack_trace_depth\", kMaxStackTraceDepth),\n \"The maximum number of stack frames to print when an \"\n \"assertion fails. The valid range is 0 through 100, inclusive.\");\n\nGTEST_DEFINE_string_(\n stream_result_to,\n internal::StringFromGTestEnv(\"stream_result_to\", \"\"),\n \"This flag specifies the host name and the port number on which to stream \"\n \"test results. Example: \\\"localhost:555\\\". The flag is effective only on \"\n \"Linux.\");\n\nGTEST_DEFINE_bool_(\n throw_on_failure,\n internal::BoolFromGTestEnv(\"throw_on_failure\", false),\n \"When this flag is specified, a failed assertion will throw an exception \"\n \"if exceptions are enabled or exit the program with a non-zero code \"\n \"otherwise. For use with an external test framework.\");\n\n#if GTEST_USE_OWN_FLAGFILE_FLAG_\nGTEST_DEFINE_string_(\n flagfile,\n internal::StringFromGTestEnv(\"flagfile\", \"\"),\n \"This flag specifies the flagfile to read command-line flags from.\");\n#endif // GTEST_USE_OWN_FLAGFILE_FLAG_\n\nnamespace internal {\n\n// Generates a random number from [0, range), using a Linear\n// Congruential Generator (LCG). Crashes if 'range' is 0 or greater\n// than kMaxRange.\nuint32_t Random::Generate(uint32_t range) {\n // These constants are the same as are used in glibc's rand(3).\n // Use wider types than necessary to prevent unsigned overflow diagnostics.\n state_ = static_cast(1103515245ULL*state_ + 12345U) % kMaxRange;\n\n GTEST_CHECK_(range > 0)\n << \"Cannot generate a number in the range [0, 0).\";\n GTEST_CHECK_(range <= kMaxRange)\n << \"Generation of a number in [0, \" << range << \") was requested, \"\n << \"but this can only generate numbers in [0, \" << kMaxRange << \").\";\n\n // Converting via modulus introduces a bit of downward bias, but\n // it's simple, and a linear congruential generator isn't too good\n // to begin with.\n return state_ % range;\n}\n\n// GTestIsInitialized() returns true if and only if the user has initialized\n// Google Test. Useful for catching the user mistake of not initializing\n// Google Test before calling RUN_ALL_TESTS().\nstatic bool GTestIsInitialized() { return GetArgvs().size() > 0; }\n\n// Iterates over a vector of TestSuites, keeping a running sum of the\n// results of calling a given int-returning method on each.\n// Returns the sum.\nstatic int SumOverTestSuiteList(const std::vector& case_list,\n int (TestSuite::*method)() const) {\n int sum = 0;\n for (size_t i = 0; i < case_list.size(); i++) {\n sum += (case_list[i]->*method)();\n }\n return sum;\n}\n\n// Returns true if and only if the test suite passed.\nstatic bool TestSuitePassed(const TestSuite* test_suite) {\n return test_suite->should_run() && test_suite->Passed();\n}\n\n// Returns true if and only if the test suite failed.\nstatic bool TestSuiteFailed(const TestSuite* test_suite) {\n return test_suite->should_run() && test_suite->Failed();\n}\n\n// Returns true if and only if test_suite contains at least one test that\n// should run.\nstatic bool ShouldRunTestSuite(const TestSuite* test_suite) {\n return test_suite->should_run();\n}\n\n// AssertHelper constructor.\nAssertHelper::AssertHelper(TestPartResult::Type type,\n const char* file,\n int line,\n const char* message)\n : data_(new AssertHelperData(type, file, line, message)) {\n}\n\nAssertHelper::~AssertHelper() {\n delete data_;\n}\n\n// Message assignment, for assertion streaming support.\nvoid AssertHelper::operator=(const Message& message) const {\n UnitTest::GetInstance()->\n AddTestPartResult(data_->type, data_->file, data_->line,\n AppendUserMessage(data_->message, message),\n UnitTest::GetInstance()->impl()\n ->CurrentOsStackTraceExceptTop(1)\n // Skips the stack frame for this function itself.\n ); // NOLINT\n}\n\nnamespace {\n\n// When TEST_P is found without a matching INSTANTIATE_TEST_SUITE_P\n// to creates test cases for it, a synthetic test case is\n// inserted to report ether an error or a log message.\n//\n// This configuration bit will likely be removed at some point.\nconstexpr bool kErrorOnUninstantiatedParameterizedTest = true;\nconstexpr bool kErrorOnUninstantiatedTypeParameterizedTest = true;\n\n// A test that fails at a given file/line location with a given message.\nclass FailureTest : public Test {\n public:\n explicit FailureTest(const CodeLocation& loc, std::string error_message,\n bool as_error)\n : loc_(loc),\n error_message_(std::move(error_message)),\n as_error_(as_error) {}\n\n void TestBody() override {\n if (as_error_) {\n AssertHelper(TestPartResult::kNonFatalFailure, loc_.file.c_str(),\n loc_.line, \"\") = Message() << error_message_;\n } else {\n std::cout << error_message_ << std::endl;\n }\n }\n\n private:\n const CodeLocation loc_;\n const std::string error_message_;\n const bool as_error_;\n};\n\n\n} // namespace\n\nstd::set* GetIgnoredParameterizedTestSuites() {\n return UnitTest::GetInstance()->impl()->ignored_parameterized_test_suites();\n}\n\n// Add a given test_suit to the list of them allow to go un-instantiated.\nMarkAsIgnored::MarkAsIgnored(const char* test_suite) {\n GetIgnoredParameterizedTestSuites()->insert(test_suite);\n}\n\n// If this parameterized test suite has no instantiations (and that\n// has not been marked as okay), emit a test case reporting that.\nvoid InsertSyntheticTestCase(const std::string& name, CodeLocation location,\n bool has_test_p) {\n const auto& ignored = *GetIgnoredParameterizedTestSuites();\n if (ignored.find(name) != ignored.end()) return;\n\n const char kMissingInstantiation[] = //\n \" is defined via TEST_P, but never instantiated. None of the test cases \"\n \"will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only \"\n \"ones provided expand to nothing.\"\n \"\\n\\n\"\n \"Ideally, TEST_P definitions should only ever be included as part of \"\n \"binaries that intend to use them. (As opposed to, for example, being \"\n \"placed in a library that may be linked in to get other utilities.)\";\n\n const char kMissingTestCase[] = //\n \" is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are \"\n \"defined via TEST_P . No test cases will run.\"\n \"\\n\\n\"\n \"Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from \"\n \"code that always depend on code that provides TEST_P. Failing to do \"\n \"so is often an indication of dead code, e.g. the last TEST_P was \"\n \"removed but the rest got left behind.\";\n\n std::string message =\n \"Parameterized test suite \" + name +\n (has_test_p ? kMissingInstantiation : kMissingTestCase) +\n \"\\n\\n\"\n \"To suppress this error for this test suite, insert the following line \"\n \"(in a non-header) in the namespace it is defined in:\"\n \"\\n\\n\"\n \"GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(\" + name + \");\";\n\n std::string full_name = \"UninstantiatedParameterizedTestSuite<\" + name + \">\";\n RegisterTest( //\n \"GoogleTestVerification\", full_name.c_str(),\n nullptr, // No type parameter.\n nullptr, // No value parameter.\n location.file.c_str(), location.line, [message, location] {\n return new FailureTest(location, message,\n kErrorOnUninstantiatedParameterizedTest);\n });\n}\n\nvoid RegisterTypeParameterizedTestSuite(const char* test_suite_name,\n CodeLocation code_location) {\n GetUnitTestImpl()->type_parameterized_test_registry().RegisterTestSuite(\n test_suite_name, code_location);\n}\n\nvoid RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) {\n GetUnitTestImpl()\n ->type_parameterized_test_registry()\n .RegisterInstantiation(case_name);\n}\n\nvoid TypeParameterizedTestSuiteRegistry::RegisterTestSuite(\n const char* test_suite_name, CodeLocation code_location) {\n suites_.emplace(std::string(test_suite_name),\n TypeParameterizedTestSuiteInfo(code_location));\n}\n\nvoid TypeParameterizedTestSuiteRegistry::RegisterInstantiation(\n const char* test_suite_name) {\n auto it = suites_.find(std::string(test_suite_name));\n if (it != suites_.end()) {\n it->second.instantiated = true;\n } else {\n GTEST_LOG_(ERROR) << \"Unknown type parameterized test suit '\"\n << test_suite_name << \"'\";\n }\n}\n\nvoid TypeParameterizedTestSuiteRegistry::CheckForInstantiations() {\n const auto& ignored = *GetIgnoredParameterizedTestSuites();\n for (const auto& testcase : suites_) {\n if (testcase.second.instantiated) continue;\n if (ignored.find(testcase.first) != ignored.end()) continue;\n\n std::string message =\n \"Type parameterized test suite \" + testcase.first +\n \" is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated \"\n \"via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run.\"\n \"\\n\\n\"\n \"Ideally, TYPED_TEST_P definitions should only ever be included as \"\n \"part of binaries that intend to use them. (As opposed to, for \"\n \"example, being placed in a library that may be linked in to get other \"\n \"utilities.)\"\n \"\\n\\n\"\n \"To suppress this error for this test suite, insert the following line \"\n \"(in a non-header) in the namespace it is defined in:\"\n \"\\n\\n\"\n \"GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(\" +\n testcase.first + \");\";\n\n std::string full_name =\n \"UninstantiatedTypeParameterizedTestSuite<\" + testcase.first + \">\";\n RegisterTest( //\n \"GoogleTestVerification\", full_name.c_str(),\n nullptr, // No type parameter.\n nullptr, // No value parameter.\n testcase.second.code_location.file.c_str(),\n testcase.second.code_location.line, [message, testcase] {\n return new FailureTest(testcase.second.code_location, message,\n kErrorOnUninstantiatedTypeParameterizedTest);\n });\n }\n}\n\n// A copy of all command line arguments. Set by InitGoogleTest().\nstatic ::std::vector g_argvs;\n\n::std::vector GetArgvs() {\n#if defined(GTEST_CUSTOM_GET_ARGVS_)\n // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or\n // ::string. This code converts it to the appropriate type.\n const auto& custom = GTEST_CUSTOM_GET_ARGVS_();\n return ::std::vector(custom.begin(), custom.end());\n#else // defined(GTEST_CUSTOM_GET_ARGVS_)\n return g_argvs;\n#endif // defined(GTEST_CUSTOM_GET_ARGVS_)\n}\n\n// Returns the current application's name, removing directory path if that\n// is present.\nFilePath GetCurrentExecutableName() {\n FilePath result;\n\n#if GTEST_OS_WINDOWS || GTEST_OS_OS2\n result.Set(FilePath(GetArgvs()[0]).RemoveExtension(\"exe\"));\n#else\n result.Set(FilePath(GetArgvs()[0]));\n#endif // GTEST_OS_WINDOWS\n\n return result.RemoveDirectoryName();\n}\n\n// Functions for processing the gtest_output flag.\n\n// Returns the output format, or \"\" for normal printed output.\nstd::string UnitTestOptions::GetOutputFormat() {\n const char* const gtest_output_flag = GTEST_FLAG(output).c_str();\n const char* const colon = strchr(gtest_output_flag, ':');\n return (colon == nullptr)\n ? std::string(gtest_output_flag)\n : std::string(gtest_output_flag,\n static_cast(colon - gtest_output_flag));\n}\n\n// Returns the name of the requested output file, or the default if none\n// was explicitly specified.\nstd::string UnitTestOptions::GetAbsolutePathToOutputFile() {\n const char* const gtest_output_flag = GTEST_FLAG(output).c_str();\n\n std::string format = GetOutputFormat();\n if (format.empty())\n format = std::string(kDefaultOutputFormat);\n\n const char* const colon = strchr(gtest_output_flag, ':');\n if (colon == nullptr)\n return internal::FilePath::MakeFileName(\n internal::FilePath(\n UnitTest::GetInstance()->original_working_dir()),\n internal::FilePath(kDefaultOutputFile), 0,\n format.c_str()).string();\n\n internal::FilePath output_name(colon + 1);\n if (!output_name.IsAbsolutePath())\n output_name = internal::FilePath::ConcatPaths(\n internal::FilePath(UnitTest::GetInstance()->original_working_dir()),\n internal::FilePath(colon + 1));\n\n if (!output_name.IsDirectory())\n return output_name.string();\n\n internal::FilePath result(internal::FilePath::GenerateUniqueFileName(\n output_name, internal::GetCurrentExecutableName(),\n GetOutputFormat().c_str()));\n return result.string();\n}\n\n// Returns true if and only if the wildcard pattern matches the string. Each\n// pattern consists of regular characters, single-character wildcards (?), and\n// multi-character wildcards (*).\n//\n// This function implements a linear-time string globbing algorithm based on\n// https://research.swtch.com/glob.\nstatic bool PatternMatchesString(const std::string& name_str,\n const char* pattern, const char* pattern_end) {\n const char* name = name_str.c_str();\n const char* const name_begin = name;\n const char* const name_end = name + name_str.size();\n\n const char* pattern_next = pattern;\n const char* name_next = name;\n\n while (pattern < pattern_end || name < name_end) {\n if (pattern < pattern_end) {\n switch (*pattern) {\n default: // Match an ordinary character.\n if (name < name_end && *name == *pattern) {\n ++pattern;\n ++name;\n continue;\n }\n break;\n case '?': // Match any single character.\n if (name < name_end) {\n ++pattern;\n ++name;\n continue;\n }\n break;\n case '*':\n // Match zero or more characters. Start by skipping over the wildcard\n // and matching zero characters from name. If that fails, restart and\n // match one more character than the last attempt.\n pattern_next = pattern;\n name_next = name + 1;\n ++pattern;\n continue;\n }\n }\n // Failed to match a character. Restart if possible.\n if (name_begin < name_next && name_next <= name_end) {\n pattern = pattern_next;\n name = name_next;\n continue;\n }\n return false;\n }\n return true;\n}\n\nbool UnitTestOptions::MatchesFilter(const std::string& name_str,\n const char* filter) {\n // The filter is a list of patterns separated by colons (:).\n const char* pattern = filter;\n while (true) {\n // Find the bounds of this pattern.\n const char* const next_sep = strchr(pattern, ':');\n const char* const pattern_end =\n next_sep != nullptr ? next_sep : pattern + strlen(pattern);\n\n // Check if this pattern matches name_str.\n if (PatternMatchesString(name_str, pattern, pattern_end)) {\n break;\n }\n\n // Give up on this pattern. However, if we found a pattern separator (:),\n // advance to the next pattern (skipping over the separator) and restart.\n if (next_sep == nullptr) {\n return false;\n }\n pattern = next_sep + 1;\n }\n return true;\n}\n\n// Returns true if and only if the user-specified filter matches the test\n// suite name and the test name.\nbool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name,\n const std::string& test_name) {\n const std::string& full_name = test_suite_name + \".\" + test_name.c_str();\n\n // Split --gtest_filter at '-', if there is one, to separate into\n // positive filter and negative filter portions\n const char* const p = GTEST_FLAG(filter).c_str();\n const char* const dash = strchr(p, '-');\n std::string positive;\n std::string negative;\n if (dash == nullptr) {\n positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter\n negative = \"\";\n } else {\n positive = std::string(p, dash); // Everything up to the dash\n negative = std::string(dash + 1); // Everything after the dash\n if (positive.empty()) {\n // Treat '-test1' as the same as '*-test1'\n positive = kUniversalFilter;\n }\n }\n\n // A filter is a colon-separated list of patterns. It matches a\n // test if any pattern in it matches the test.\n return (MatchesFilter(full_name, positive.c_str()) &&\n !MatchesFilter(full_name, negative.c_str()));\n}\n\n#if GTEST_HAS_SEH\n// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the\n// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.\n// This function is useful as an __except condition.\nint UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {\n // Google Test should handle a SEH exception if:\n // 1. the user wants it to, AND\n // 2. this is not a breakpoint exception, AND\n // 3. this is not a C++ exception (VC++ implements them via SEH,\n // apparently).\n //\n // SEH exception code for C++ exceptions.\n // (see http://support.microsoft.com/kb/185294 for more information).\n const DWORD kCxxExceptionCode = 0xe06d7363;\n\n bool should_handle = true;\n\n if (!GTEST_FLAG(catch_exceptions))\n should_handle = false;\n else if (exception_code == EXCEPTION_BREAKPOINT)\n should_handle = false;\n else if (exception_code == kCxxExceptionCode)\n should_handle = false;\n\n return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;\n}\n#endif // GTEST_HAS_SEH\n\n} // namespace internal\n\n// The c'tor sets this object as the test part result reporter used by\n// Google Test. The 'result' parameter specifies where to report the\n// results. Intercepts only failures from the current thread.\nScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(\n TestPartResultArray* result)\n : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),\n result_(result) {\n Init();\n}\n\n// The c'tor sets this object as the test part result reporter used by\n// Google Test. The 'result' parameter specifies where to report the\n// results.\nScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(\n InterceptMode intercept_mode, TestPartResultArray* result)\n : intercept_mode_(intercept_mode),\n result_(result) {\n Init();\n}\n\nvoid ScopedFakeTestPartResultReporter::Init() {\n internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n if (intercept_mode_ == INTERCEPT_ALL_THREADS) {\n old_reporter_ = impl->GetGlobalTestPartResultReporter();\n impl->SetGlobalTestPartResultReporter(this);\n } else {\n old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();\n impl->SetTestPartResultReporterForCurrentThread(this);\n }\n}\n\n// The d'tor restores the test part result reporter used by Google Test\n// before.\nScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {\n internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n if (intercept_mode_ == INTERCEPT_ALL_THREADS) {\n impl->SetGlobalTestPartResultReporter(old_reporter_);\n } else {\n impl->SetTestPartResultReporterForCurrentThread(old_reporter_);\n }\n}\n\n// Increments the test part result count and remembers the result.\n// This method is from the TestPartResultReporterInterface interface.\nvoid ScopedFakeTestPartResultReporter::ReportTestPartResult(\n const TestPartResult& result) {\n result_->Append(result);\n}\n\nnamespace internal {\n\n// Returns the type ID of ::testing::Test. We should always call this\n// instead of GetTypeId< ::testing::Test>() to get the type ID of\n// testing::Test. This is to work around a suspected linker bug when\n// using Google Test as a framework on Mac OS X. The bug causes\n// GetTypeId< ::testing::Test>() to return different values depending\n// on whether the call is from the Google Test framework itself or\n// from user test code. GetTestTypeId() is guaranteed to always\n// return the same value, as it always calls GetTypeId<>() from the\n// gtest.cc, which is within the Google Test framework.\nTypeId GetTestTypeId() {\n return GetTypeId();\n}\n\n// The value of GetTestTypeId() as seen from within the Google Test\n// library. This is solely for testing GetTestTypeId().\nextern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();\n\n// This predicate-formatter checks that 'results' contains a test part\n// failure of the given type and that the failure message contains the\n// given substring.\nstatic AssertionResult HasOneFailure(const char* /* results_expr */,\n const char* /* type_expr */,\n const char* /* substr_expr */,\n const TestPartResultArray& results,\n TestPartResult::Type type,\n const std::string& substr) {\n const std::string expected(type == TestPartResult::kFatalFailure ?\n \"1 fatal failure\" :\n \"1 non-fatal failure\");\n Message msg;\n if (results.size() != 1) {\n msg << \"Expected: \" << expected << \"\\n\"\n << \" Actual: \" << results.size() << \" failures\";\n for (int i = 0; i < results.size(); i++) {\n msg << \"\\n\" << results.GetTestPartResult(i);\n }\n return AssertionFailure() << msg;\n }\n\n const TestPartResult& r = results.GetTestPartResult(0);\n if (r.type() != type) {\n return AssertionFailure() << \"Expected: \" << expected << \"\\n\"\n << \" Actual:\\n\"\n << r;\n }\n\n if (strstr(r.message(), substr.c_str()) == nullptr) {\n return AssertionFailure() << \"Expected: \" << expected << \" containing \\\"\"\n << substr << \"\\\"\\n\"\n << \" Actual:\\n\"\n << r;\n }\n\n return AssertionSuccess();\n}\n\n// The constructor of SingleFailureChecker remembers where to look up\n// test part results, what type of failure we expect, and what\n// substring the failure message should contain.\nSingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,\n TestPartResult::Type type,\n const std::string& substr)\n : results_(results), type_(type), substr_(substr) {}\n\n// The destructor of SingleFailureChecker verifies that the given\n// TestPartResultArray contains exactly one failure that has the given\n// type and contains the given substring. If that's not the case, a\n// non-fatal failure will be generated.\nSingleFailureChecker::~SingleFailureChecker() {\n EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);\n}\n\nDefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(\n UnitTestImpl* unit_test) : unit_test_(unit_test) {}\n\nvoid DefaultGlobalTestPartResultReporter::ReportTestPartResult(\n const TestPartResult& result) {\n unit_test_->current_test_result()->AddTestPartResult(result);\n unit_test_->listeners()->repeater()->OnTestPartResult(result);\n}\n\nDefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(\n UnitTestImpl* unit_test) : unit_test_(unit_test) {}\n\nvoid DefaultPerThreadTestPartResultReporter::ReportTestPartResult(\n const TestPartResult& result) {\n unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);\n}\n\n// Returns the global test part result reporter.\nTestPartResultReporterInterface*\nUnitTestImpl::GetGlobalTestPartResultReporter() {\n internal::MutexLock lock(&global_test_part_result_reporter_mutex_);\n return global_test_part_result_repoter_;\n}\n\n// Sets the global test part result reporter.\nvoid UnitTestImpl::SetGlobalTestPartResultReporter(\n TestPartResultReporterInterface* reporter) {\n internal::MutexLock lock(&global_test_part_result_reporter_mutex_);\n global_test_part_result_repoter_ = reporter;\n}\n\n// Returns the test part result reporter for the current thread.\nTestPartResultReporterInterface*\nUnitTestImpl::GetTestPartResultReporterForCurrentThread() {\n return per_thread_test_part_result_reporter_.get();\n}\n\n// Sets the test part result reporter for the current thread.\nvoid UnitTestImpl::SetTestPartResultReporterForCurrentThread(\n TestPartResultReporterInterface* reporter) {\n per_thread_test_part_result_reporter_.set(reporter);\n}\n\n// Gets the number of successful test suites.\nint UnitTestImpl::successful_test_suite_count() const {\n return CountIf(test_suites_, TestSuitePassed);\n}\n\n// Gets the number of failed test suites.\nint UnitTestImpl::failed_test_suite_count() const {\n return CountIf(test_suites_, TestSuiteFailed);\n}\n\n// Gets the number of all test suites.\nint UnitTestImpl::total_test_suite_count() const {\n return static_cast(test_suites_.size());\n}\n\n// Gets the number of all test suites that contain at least one test\n// that should run.\nint UnitTestImpl::test_suite_to_run_count() const {\n return CountIf(test_suites_, ShouldRunTestSuite);\n}\n\n// Gets the number of successful tests.\nint UnitTestImpl::successful_test_count() const {\n return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count);\n}\n\n// Gets the number of skipped tests.\nint UnitTestImpl::skipped_test_count() const {\n return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count);\n}\n\n// Gets the number of failed tests.\nint UnitTestImpl::failed_test_count() const {\n return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count);\n}\n\n// Gets the number of disabled tests that will be reported in the XML report.\nint UnitTestImpl::reportable_disabled_test_count() const {\n return SumOverTestSuiteList(test_suites_,\n &TestSuite::reportable_disabled_test_count);\n}\n\n// Gets the number of disabled tests.\nint UnitTestImpl::disabled_test_count() const {\n return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count);\n}\n\n// Gets the number of tests to be printed in the XML report.\nint UnitTestImpl::reportable_test_count() const {\n return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count);\n}\n\n// Gets the number of all tests.\nint UnitTestImpl::total_test_count() const {\n return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count);\n}\n\n// Gets the number of tests that should run.\nint UnitTestImpl::test_to_run_count() const {\n return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count);\n}\n\n// Returns the current OS stack trace as an std::string.\n//\n// The maximum number of stack frames to be included is specified by\n// the gtest_stack_trace_depth flag. The skip_count parameter\n// specifies the number of top frames to be skipped, which doesn't\n// count against the number of frames to be included.\n//\n// For example, if Foo() calls Bar(), which in turn calls\n// CurrentOsStackTraceExceptTop(1), Foo() will be included in the\n// trace but Bar() and CurrentOsStackTraceExceptTop() won't.\nstd::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {\n return os_stack_trace_getter()->CurrentStackTrace(\n static_cast(GTEST_FLAG(stack_trace_depth)),\n skip_count + 1\n // Skips the user-specified number of frames plus this function\n // itself.\n ); // NOLINT\n}\n\n// A helper class for measuring elapsed times.\nclass Timer {\n public:\n Timer() : start_(std::chrono::steady_clock::now()) {}\n\n // Return time elapsed in milliseconds since the timer was created.\n TimeInMillis Elapsed() {\n return std::chrono::duration_cast(\n std::chrono::steady_clock::now() - start_)\n .count();\n }\n\n private:\n std::chrono::steady_clock::time_point start_;\n};\n\n// Returns a timestamp as milliseconds since the epoch. Note this time may jump\n// around subject to adjustments by the system, to measure elapsed time use\n// Timer instead.\nTimeInMillis GetTimeInMillis() {\n return std::chrono::duration_cast(\n std::chrono::system_clock::now() -\n std::chrono::system_clock::from_time_t(0))\n .count();\n}\n\n// Utilities\n\n// class String.\n\n#if GTEST_OS_WINDOWS_MOBILE\n// Creates a UTF-16 wide string from the given ANSI string, allocating\n// memory using new. The caller is responsible for deleting the return\n// value using delete[]. Returns the wide string, or NULL if the\n// input is NULL.\nLPCWSTR String::AnsiToUtf16(const char* ansi) {\n if (!ansi) return nullptr;\n const int length = strlen(ansi);\n const int unicode_length =\n MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0);\n WCHAR* unicode = new WCHAR[unicode_length + 1];\n MultiByteToWideChar(CP_ACP, 0, ansi, length,\n unicode, unicode_length);\n unicode[unicode_length] = 0;\n return unicode;\n}\n\n// Creates an ANSI string from the given wide string, allocating\n// memory using new. The caller is responsible for deleting the return\n// value using delete[]. Returns the ANSI string, or NULL if the\n// input is NULL.\nconst char* String::Utf16ToAnsi(LPCWSTR utf16_str) {\n if (!utf16_str) return nullptr;\n const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr,\n 0, nullptr, nullptr);\n char* ansi = new char[ansi_length + 1];\n WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr,\n nullptr);\n ansi[ansi_length] = 0;\n return ansi;\n}\n\n#endif // GTEST_OS_WINDOWS_MOBILE\n\n// Compares two C strings. Returns true if and only if they have the same\n// content.\n//\n// Unlike strcmp(), this function can handle NULL argument(s). A NULL\n// C string is considered different to any non-NULL C string,\n// including the empty string.\nbool String::CStringEquals(const char * lhs, const char * rhs) {\n if (lhs == nullptr) return rhs == nullptr;\n\n if (rhs == nullptr) return false;\n\n return strcmp(lhs, rhs) == 0;\n}\n\n#if GTEST_HAS_STD_WSTRING\n\n// Converts an array of wide chars to a narrow string using the UTF-8\n// encoding, and streams the result to the given Message object.\nstatic void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,\n Message* msg) {\n for (size_t i = 0; i != length; ) { // NOLINT\n if (wstr[i] != L'\\0') {\n *msg << WideStringToUtf8(wstr + i, static_cast(length - i));\n while (i != length && wstr[i] != L'\\0')\n i++;\n } else {\n *msg << '\\0';\n i++;\n }\n }\n}\n\n#endif // GTEST_HAS_STD_WSTRING\n\nvoid SplitString(const ::std::string& str, char delimiter,\n ::std::vector< ::std::string>* dest) {\n ::std::vector< ::std::string> parsed;\n ::std::string::size_type pos = 0;\n while (::testing::internal::AlwaysTrue()) {\n const ::std::string::size_type colon = str.find(delimiter, pos);\n if (colon == ::std::string::npos) {\n parsed.push_back(str.substr(pos));\n break;\n } else {\n parsed.push_back(str.substr(pos, colon - pos));\n pos = colon + 1;\n }\n }\n dest->swap(parsed);\n}\n\n} // namespace internal\n\n// Constructs an empty Message.\n// We allocate the stringstream separately because otherwise each use of\n// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's\n// stack frame leading to huge stack frames in some cases; gcc does not reuse\n// the stack space.\nMessage::Message() : ss_(new ::std::stringstream) {\n // By default, we want there to be enough precision when printing\n // a double to a Message.\n *ss_ << std::setprecision(std::numeric_limits::digits10 + 2);\n}\n\n// These two overloads allow streaming a wide C string to a Message\n// using the UTF-8 encoding.\nMessage& Message::operator <<(const wchar_t* wide_c_str) {\n return *this << internal::String::ShowWideCString(wide_c_str);\n}\nMessage& Message::operator <<(wchar_t* wide_c_str) {\n return *this << internal::String::ShowWideCString(wide_c_str);\n}\n\n#if GTEST_HAS_STD_WSTRING\n// Converts the given wide string to a narrow string using the UTF-8\n// encoding, and streams the result to this Message object.\nMessage& Message::operator <<(const ::std::wstring& wstr) {\n internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);\n return *this;\n}\n#endif // GTEST_HAS_STD_WSTRING\n\n// Gets the text streamed to this object so far as an std::string.\n// Each '\\0' character in the buffer is replaced with \"\\\\0\".\nstd::string Message::GetString() const {\n return internal::StringStreamToString(ss_.get());\n}\n\n// AssertionResult constructors.\n// Used in EXPECT_TRUE/FALSE(assertion_result).\nAssertionResult::AssertionResult(const AssertionResult& other)\n : success_(other.success_),\n message_(other.message_.get() != nullptr\n ? new ::std::string(*other.message_)\n : static_cast< ::std::string*>(nullptr)) {}\n\n// Swaps two AssertionResults.\nvoid AssertionResult::swap(AssertionResult& other) {\n using std::swap;\n swap(success_, other.success_);\n swap(message_, other.message_);\n}\n\n// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.\nAssertionResult AssertionResult::operator!() const {\n AssertionResult negation(!success_);\n if (message_.get() != nullptr) negation << *message_;\n return negation;\n}\n\n// Makes a successful assertion result.\nAssertionResult AssertionSuccess() {\n return AssertionResult(true);\n}\n\n// Makes a failed assertion result.\nAssertionResult AssertionFailure() {\n return AssertionResult(false);\n}\n\n// Makes a failed assertion result with the given failure message.\n// Deprecated; use AssertionFailure() << message.\nAssertionResult AssertionFailure(const Message& message) {\n return AssertionFailure() << message;\n}\n\nnamespace internal {\n\nnamespace edit_distance {\nstd::vector CalculateOptimalEdits(const std::vector& left,\n const std::vector& right) {\n std::vector > costs(\n left.size() + 1, std::vector(right.size() + 1));\n std::vector > best_move(\n left.size() + 1, std::vector(right.size() + 1));\n\n // Populate for empty right.\n for (size_t l_i = 0; l_i < costs.size(); ++l_i) {\n costs[l_i][0] = static_cast(l_i);\n best_move[l_i][0] = kRemove;\n }\n // Populate for empty left.\n for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {\n costs[0][r_i] = static_cast(r_i);\n best_move[0][r_i] = kAdd;\n }\n\n for (size_t l_i = 0; l_i < left.size(); ++l_i) {\n for (size_t r_i = 0; r_i < right.size(); ++r_i) {\n if (left[l_i] == right[r_i]) {\n // Found a match. Consume it.\n costs[l_i + 1][r_i + 1] = costs[l_i][r_i];\n best_move[l_i + 1][r_i + 1] = kMatch;\n continue;\n }\n\n const double add = costs[l_i + 1][r_i];\n const double remove = costs[l_i][r_i + 1];\n const double replace = costs[l_i][r_i];\n if (add < remove && add < replace) {\n costs[l_i + 1][r_i + 1] = add + 1;\n best_move[l_i + 1][r_i + 1] = kAdd;\n } else if (remove < add && remove < replace) {\n costs[l_i + 1][r_i + 1] = remove + 1;\n best_move[l_i + 1][r_i + 1] = kRemove;\n } else {\n // We make replace a little more expensive than add/remove to lower\n // their priority.\n costs[l_i + 1][r_i + 1] = replace + 1.00001;\n best_move[l_i + 1][r_i + 1] = kReplace;\n }\n }\n }\n\n // Reconstruct the best path. We do it in reverse order.\n std::vector best_path;\n for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {\n EditType move = best_move[l_i][r_i];\n best_path.push_back(move);\n l_i -= move != kAdd;\n r_i -= move != kRemove;\n }\n std::reverse(best_path.begin(), best_path.end());\n return best_path;\n}\n\nnamespace {\n\n// Helper class to convert string into ids with deduplication.\nclass InternalStrings {\n public:\n size_t GetId(const std::string& str) {\n IdMap::iterator it = ids_.find(str);\n if (it != ids_.end()) return it->second;\n size_t id = ids_.size();\n return ids_[str] = id;\n }\n\n private:\n typedef std::map IdMap;\n IdMap ids_;\n};\n\n} // namespace\n\nstd::vector CalculateOptimalEdits(\n const std::vector& left,\n const std::vector& right) {\n std::vector left_ids, right_ids;\n {\n InternalStrings intern_table;\n for (size_t i = 0; i < left.size(); ++i) {\n left_ids.push_back(intern_table.GetId(left[i]));\n }\n for (size_t i = 0; i < right.size(); ++i) {\n right_ids.push_back(intern_table.GetId(right[i]));\n }\n }\n return CalculateOptimalEdits(left_ids, right_ids);\n}\n\nnamespace {\n\n// Helper class that holds the state for one hunk and prints it out to the\n// stream.\n// It reorders adds/removes when possible to group all removes before all\n// adds. It also adds the hunk header before printint into the stream.\nclass Hunk {\n public:\n Hunk(size_t left_start, size_t right_start)\n : left_start_(left_start),\n right_start_(right_start),\n adds_(),\n removes_(),\n common_() {}\n\n void PushLine(char edit, const char* line) {\n switch (edit) {\n case ' ':\n ++common_;\n FlushEdits();\n hunk_.push_back(std::make_pair(' ', line));\n break;\n case '-':\n ++removes_;\n hunk_removes_.push_back(std::make_pair('-', line));\n break;\n case '+':\n ++adds_;\n hunk_adds_.push_back(std::make_pair('+', line));\n break;\n }\n }\n\n void PrintTo(std::ostream* os) {\n PrintHeader(os);\n FlushEdits();\n for (std::list >::const_iterator it =\n hunk_.begin();\n it != hunk_.end(); ++it) {\n *os << it->first << it->second << \"\\n\";\n }\n }\n\n bool has_edits() const { return adds_ || removes_; }\n\n private:\n void FlushEdits() {\n hunk_.splice(hunk_.end(), hunk_removes_);\n hunk_.splice(hunk_.end(), hunk_adds_);\n }\n\n // Print a unified diff header for one hunk.\n // The format is\n // \"@@ -, +, @@\"\n // where the left/right parts are omitted if unnecessary.\n void PrintHeader(std::ostream* ss) const {\n *ss << \"@@ \";\n if (removes_) {\n *ss << \"-\" << left_start_ << \",\" << (removes_ + common_);\n }\n if (removes_ && adds_) {\n *ss << \" \";\n }\n if (adds_) {\n *ss << \"+\" << right_start_ << \",\" << (adds_ + common_);\n }\n *ss << \" @@\\n\";\n }\n\n size_t left_start_, right_start_;\n size_t adds_, removes_, common_;\n std::list > hunk_, hunk_adds_, hunk_removes_;\n};\n\n} // namespace\n\n// Create a list of diff hunks in Unified diff format.\n// Each hunk has a header generated by PrintHeader above plus a body with\n// lines prefixed with ' ' for no change, '-' for deletion and '+' for\n// addition.\n// 'context' represents the desired unchanged prefix/suffix around the diff.\n// If two hunks are close enough that their contexts overlap, then they are\n// joined into one hunk.\nstd::string CreateUnifiedDiff(const std::vector& left,\n const std::vector& right,\n size_t context) {\n const std::vector edits = CalculateOptimalEdits(left, right);\n\n size_t l_i = 0, r_i = 0, edit_i = 0;\n std::stringstream ss;\n while (edit_i < edits.size()) {\n // Find first edit.\n while (edit_i < edits.size() && edits[edit_i] == kMatch) {\n ++l_i;\n ++r_i;\n ++edit_i;\n }\n\n // Find the first line to include in the hunk.\n const size_t prefix_context = std::min(l_i, context);\n Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);\n for (size_t i = prefix_context; i > 0; --i) {\n hunk.PushLine(' ', left[l_i - i].c_str());\n }\n\n // Iterate the edits until we found enough suffix for the hunk or the input\n // is over.\n size_t n_suffix = 0;\n for (; edit_i < edits.size(); ++edit_i) {\n if (n_suffix >= context) {\n // Continue only if the next hunk is very close.\n auto it = edits.begin() + static_cast(edit_i);\n while (it != edits.end() && *it == kMatch) ++it;\n if (it == edits.end() ||\n static_cast(it - edits.begin()) - edit_i >= context) {\n // There is no next edit or it is too far away.\n break;\n }\n }\n\n EditType edit = edits[edit_i];\n // Reset count when a non match is found.\n n_suffix = edit == kMatch ? n_suffix + 1 : 0;\n\n if (edit == kMatch || edit == kRemove || edit == kReplace) {\n hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());\n }\n if (edit == kAdd || edit == kReplace) {\n hunk.PushLine('+', right[r_i].c_str());\n }\n\n // Advance indices, depending on edit type.\n l_i += edit != kAdd;\n r_i += edit != kRemove;\n }\n\n if (!hunk.has_edits()) {\n // We are done. We don't want this hunk.\n break;\n }\n\n hunk.PrintTo(&ss);\n }\n return ss.str();\n}\n\n} // namespace edit_distance\n\nnamespace {\n\n// The string representation of the values received in EqFailure() are already\n// escaped. Split them on escaped '\\n' boundaries. Leave all other escaped\n// characters the same.\nstd::vector SplitEscapedString(const std::string& str) {\n std::vector lines;\n size_t start = 0, end = str.size();\n if (end > 2 && str[0] == '\"' && str[end - 1] == '\"') {\n ++start;\n --end;\n }\n bool escaped = false;\n for (size_t i = start; i + 1 < end; ++i) {\n if (escaped) {\n escaped = false;\n if (str[i] == 'n') {\n lines.push_back(str.substr(start, i - start - 1));\n start = i + 1;\n }\n } else {\n escaped = str[i] == '\\\\';\n }\n }\n lines.push_back(str.substr(start, end - start));\n return lines;\n}\n\n} // namespace\n\n// Constructs and returns the message for an equality assertion\n// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.\n//\n// The first four parameters are the expressions used in the assertion\n// and their values, as strings. For example, for ASSERT_EQ(foo, bar)\n// where foo is 5 and bar is 6, we have:\n//\n// lhs_expression: \"foo\"\n// rhs_expression: \"bar\"\n// lhs_value: \"5\"\n// rhs_value: \"6\"\n//\n// The ignoring_case parameter is true if and only if the assertion is a\n// *_STRCASEEQ*. When it's true, the string \"Ignoring case\" will\n// be inserted into the message.\nAssertionResult EqFailure(const char* lhs_expression,\n const char* rhs_expression,\n const std::string& lhs_value,\n const std::string& rhs_value,\n bool ignoring_case) {\n Message msg;\n msg << \"Expected equality of these values:\";\n msg << \"\\n \" << lhs_expression;\n if (lhs_value != lhs_expression) {\n msg << \"\\n Which is: \" << lhs_value;\n }\n msg << \"\\n \" << rhs_expression;\n if (rhs_value != rhs_expression) {\n msg << \"\\n Which is: \" << rhs_value;\n }\n\n if (ignoring_case) {\n msg << \"\\nIgnoring case\";\n }\n\n if (!lhs_value.empty() && !rhs_value.empty()) {\n const std::vector lhs_lines =\n SplitEscapedString(lhs_value);\n const std::vector rhs_lines =\n SplitEscapedString(rhs_value);\n if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {\n msg << \"\\nWith diff:\\n\"\n << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);\n }\n }\n\n return AssertionFailure() << msg;\n}\n\n// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.\nstd::string GetBoolAssertionFailureMessage(\n const AssertionResult& assertion_result,\n const char* expression_text,\n const char* actual_predicate_value,\n const char* expected_predicate_value) {\n const char* actual_message = assertion_result.message();\n Message msg;\n msg << \"Value of: \" << expression_text\n << \"\\n Actual: \" << actual_predicate_value;\n if (actual_message[0] != '\\0')\n msg << \" (\" << actual_message << \")\";\n msg << \"\\nExpected: \" << expected_predicate_value;\n return msg.GetString();\n}\n\n// Helper function for implementing ASSERT_NEAR.\nAssertionResult DoubleNearPredFormat(const char* expr1,\n const char* expr2,\n const char* abs_error_expr,\n double val1,\n double val2,\n double abs_error) {\n const double diff = fabs(val1 - val2);\n if (diff <= abs_error) return AssertionSuccess();\n\n // Find the value which is closest to zero.\n const double min_abs = std::min(fabs(val1), fabs(val2));\n // Find the distance to the next double from that value.\n const double epsilon =\n nextafter(min_abs, std::numeric_limits::infinity()) - min_abs;\n // Detect the case where abs_error is so small that EXPECT_NEAR is\n // effectively the same as EXPECT_EQUAL, and give an informative error\n // message so that the situation can be more easily understood without\n // requiring exotic floating-point knowledge.\n // Don't do an epsilon check if abs_error is zero because that implies\n // that an equality check was actually intended.\n if (!(std::isnan)(val1) && !(std::isnan)(val2) && abs_error > 0 &&\n abs_error < epsilon) {\n return AssertionFailure()\n << \"The difference between \" << expr1 << \" and \" << expr2 << \" is \"\n << diff << \", where\\n\"\n << expr1 << \" evaluates to \" << val1 << \",\\n\"\n << expr2 << \" evaluates to \" << val2 << \".\\nThe abs_error parameter \"\n << abs_error_expr << \" evaluates to \" << abs_error\n << \" which is smaller than the minimum distance between doubles for \"\n \"numbers of this magnitude which is \"\n << epsilon\n << \", thus making this EXPECT_NEAR check equivalent to \"\n \"EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead.\";\n }\n return AssertionFailure()\n << \"The difference between \" << expr1 << \" and \" << expr2\n << \" is \" << diff << \", which exceeds \" << abs_error_expr << \", where\\n\"\n << expr1 << \" evaluates to \" << val1 << \",\\n\"\n << expr2 << \" evaluates to \" << val2 << \", and\\n\"\n << abs_error_expr << \" evaluates to \" << abs_error << \".\";\n}\n\n\n// Helper template for implementing FloatLE() and DoubleLE().\ntemplate \nAssertionResult FloatingPointLE(const char* expr1,\n const char* expr2,\n RawType val1,\n RawType val2) {\n // Returns success if val1 is less than val2,\n if (val1 < val2) {\n return AssertionSuccess();\n }\n\n // or if val1 is almost equal to val2.\n const FloatingPoint lhs(val1), rhs(val2);\n if (lhs.AlmostEquals(rhs)) {\n return AssertionSuccess();\n }\n\n // Note that the above two checks will both fail if either val1 or\n // val2 is NaN, as the IEEE floating-point standard requires that\n // any predicate involving a NaN must return false.\n\n ::std::stringstream val1_ss;\n val1_ss << std::setprecision(std::numeric_limits::digits10 + 2)\n << val1;\n\n ::std::stringstream val2_ss;\n val2_ss << std::setprecision(std::numeric_limits::digits10 + 2)\n << val2;\n\n return AssertionFailure()\n << \"Expected: (\" << expr1 << \") <= (\" << expr2 << \")\\n\"\n << \" Actual: \" << StringStreamToString(&val1_ss) << \" vs \"\n << StringStreamToString(&val2_ss);\n}\n\n} // namespace internal\n\n// Asserts that val1 is less than, or almost equal to, val2. Fails\n// otherwise. In particular, it fails if either val1 or val2 is NaN.\nAssertionResult FloatLE(const char* expr1, const char* expr2,\n float val1, float val2) {\n return internal::FloatingPointLE(expr1, expr2, val1, val2);\n}\n\n// Asserts that val1 is less than, or almost equal to, val2. Fails\n// otherwise. In particular, it fails if either val1 or val2 is NaN.\nAssertionResult DoubleLE(const char* expr1, const char* expr2,\n double val1, double val2) {\n return internal::FloatingPointLE(expr1, expr2, val1, val2);\n}\n\nnamespace internal {\n\n// The helper function for {ASSERT|EXPECT}_STREQ.\nAssertionResult CmpHelperSTREQ(const char* lhs_expression,\n const char* rhs_expression,\n const char* lhs,\n const char* rhs) {\n if (String::CStringEquals(lhs, rhs)) {\n return AssertionSuccess();\n }\n\n return EqFailure(lhs_expression,\n rhs_expression,\n PrintToString(lhs),\n PrintToString(rhs),\n false);\n}\n\n// The helper function for {ASSERT|EXPECT}_STRCASEEQ.\nAssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,\n const char* rhs_expression,\n const char* lhs,\n const char* rhs) {\n if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {\n return AssertionSuccess();\n }\n\n return EqFailure(lhs_expression,\n rhs_expression,\n PrintToString(lhs),\n PrintToString(rhs),\n true);\n}\n\n// The helper function for {ASSERT|EXPECT}_STRNE.\nAssertionResult CmpHelperSTRNE(const char* s1_expression,\n const char* s2_expression,\n const char* s1,\n const char* s2) {\n if (!String::CStringEquals(s1, s2)) {\n return AssertionSuccess();\n } else {\n return AssertionFailure() << \"Expected: (\" << s1_expression << \") != (\"\n << s2_expression << \"), actual: \\\"\"\n << s1 << \"\\\" vs \\\"\" << s2 << \"\\\"\";\n }\n}\n\n// The helper function for {ASSERT|EXPECT}_STRCASENE.\nAssertionResult CmpHelperSTRCASENE(const char* s1_expression,\n const char* s2_expression,\n const char* s1,\n const char* s2) {\n if (!String::CaseInsensitiveCStringEquals(s1, s2)) {\n return AssertionSuccess();\n } else {\n return AssertionFailure()\n << \"Expected: (\" << s1_expression << \") != (\"\n << s2_expression << \") (ignoring case), actual: \\\"\"\n << s1 << \"\\\" vs \\\"\" << s2 << \"\\\"\";\n }\n}\n\n} // namespace internal\n\nnamespace {\n\n// Helper functions for implementing IsSubString() and IsNotSubstring().\n\n// This group of overloaded functions return true if and only if needle\n// is a substring of haystack. NULL is considered a substring of\n// itself only.\n\nbool IsSubstringPred(const char* needle, const char* haystack) {\n if (needle == nullptr || haystack == nullptr) return needle == haystack;\n\n return strstr(haystack, needle) != nullptr;\n}\n\nbool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {\n if (needle == nullptr || haystack == nullptr) return needle == haystack;\n\n return wcsstr(haystack, needle) != nullptr;\n}\n\n// StringType here can be either ::std::string or ::std::wstring.\ntemplate \nbool IsSubstringPred(const StringType& needle,\n const StringType& haystack) {\n return haystack.find(needle) != StringType::npos;\n}\n\n// This function implements either IsSubstring() or IsNotSubstring(),\n// depending on the value of the expected_to_be_substring parameter.\n// StringType here can be const char*, const wchar_t*, ::std::string,\n// or ::std::wstring.\ntemplate \nAssertionResult IsSubstringImpl(\n bool expected_to_be_substring,\n const char* needle_expr, const char* haystack_expr,\n const StringType& needle, const StringType& haystack) {\n if (IsSubstringPred(needle, haystack) == expected_to_be_substring)\n return AssertionSuccess();\n\n const bool is_wide_string = sizeof(needle[0]) > 1;\n const char* const begin_string_quote = is_wide_string ? \"L\\\"\" : \"\\\"\";\n return AssertionFailure()\n << \"Value of: \" << needle_expr << \"\\n\"\n << \" Actual: \" << begin_string_quote << needle << \"\\\"\\n\"\n << \"Expected: \" << (expected_to_be_substring ? \"\" : \"not \")\n << \"a substring of \" << haystack_expr << \"\\n\"\n << \"Which is: \" << begin_string_quote << haystack << \"\\\"\";\n}\n\n} // namespace\n\n// IsSubstring() and IsNotSubstring() check whether needle is a\n// substring of haystack (NULL is considered a substring of itself\n// only), and return an appropriate error message when they fail.\n\nAssertionResult IsSubstring(\n const char* needle_expr, const char* haystack_expr,\n const char* needle, const char* haystack) {\n return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);\n}\n\nAssertionResult IsSubstring(\n const char* needle_expr, const char* haystack_expr,\n const wchar_t* needle, const wchar_t* haystack) {\n return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);\n}\n\nAssertionResult IsNotSubstring(\n const char* needle_expr, const char* haystack_expr,\n const char* needle, const char* haystack) {\n return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);\n}\n\nAssertionResult IsNotSubstring(\n const char* needle_expr, const char* haystack_expr,\n const wchar_t* needle, const wchar_t* haystack) {\n return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);\n}\n\nAssertionResult IsSubstring(\n const char* needle_expr, const char* haystack_expr,\n const ::std::string& needle, const ::std::string& haystack) {\n return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);\n}\n\nAssertionResult IsNotSubstring(\n const char* needle_expr, const char* haystack_expr,\n const ::std::string& needle, const ::std::string& haystack) {\n return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);\n}\n\n#if GTEST_HAS_STD_WSTRING\nAssertionResult IsSubstring(\n const char* needle_expr, const char* haystack_expr,\n const ::std::wstring& needle, const ::std::wstring& haystack) {\n return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);\n}\n\nAssertionResult IsNotSubstring(\n const char* needle_expr, const char* haystack_expr,\n const ::std::wstring& needle, const ::std::wstring& haystack) {\n return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);\n}\n#endif // GTEST_HAS_STD_WSTRING\n\nnamespace internal {\n\n#if GTEST_OS_WINDOWS\n\nnamespace {\n\n// Helper function for IsHRESULT{SuccessFailure} predicates\nAssertionResult HRESULTFailureHelper(const char* expr,\n const char* expected,\n long hr) { // NOLINT\n# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE\n\n // Windows CE doesn't support FormatMessage.\n const char error_text[] = \"\";\n\n# else\n\n // Looks up the human-readable system message for the HRESULT code\n // and since we're not passing any params to FormatMessage, we don't\n // want inserts expanded.\n const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |\n FORMAT_MESSAGE_IGNORE_INSERTS;\n const DWORD kBufSize = 4096;\n // Gets the system's human readable message string for this HRESULT.\n char error_text[kBufSize] = { '\\0' };\n DWORD message_length = ::FormatMessageA(kFlags,\n 0, // no source, we're asking system\n static_cast(hr), // the error\n 0, // no line width restrictions\n error_text, // output buffer\n kBufSize, // buf size\n nullptr); // no arguments for inserts\n // Trims tailing white space (FormatMessage leaves a trailing CR-LF)\n for (; message_length && IsSpace(error_text[message_length - 1]);\n --message_length) {\n error_text[message_length - 1] = '\\0';\n }\n\n# endif // GTEST_OS_WINDOWS_MOBILE\n\n const std::string error_hex(\"0x\" + String::FormatHexInt(hr));\n return ::testing::AssertionFailure()\n << \"Expected: \" << expr << \" \" << expected << \".\\n\"\n << \" Actual: \" << error_hex << \" \" << error_text << \"\\n\";\n}\n\n} // namespace\n\nAssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT\n if (SUCCEEDED(hr)) {\n return AssertionSuccess();\n }\n return HRESULTFailureHelper(expr, \"succeeds\", hr);\n}\n\nAssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT\n if (FAILED(hr)) {\n return AssertionSuccess();\n }\n return HRESULTFailureHelper(expr, \"fails\", hr);\n}\n\n#endif // GTEST_OS_WINDOWS\n\n// Utility functions for encoding Unicode text (wide strings) in\n// UTF-8.\n\n// A Unicode code-point can have up to 21 bits, and is encoded in UTF-8\n// like this:\n//\n// Code-point length Encoding\n// 0 - 7 bits 0xxxxxxx\n// 8 - 11 bits 110xxxxx 10xxxxxx\n// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx\n// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n\n// The maximum code-point a one-byte UTF-8 sequence can represent.\nconstexpr uint32_t kMaxCodePoint1 = (static_cast(1) << 7) - 1;\n\n// The maximum code-point a two-byte UTF-8 sequence can represent.\nconstexpr uint32_t kMaxCodePoint2 = (static_cast(1) << (5 + 6)) - 1;\n\n// The maximum code-point a three-byte UTF-8 sequence can represent.\nconstexpr uint32_t kMaxCodePoint3 = (static_cast(1) << (4 + 2*6)) - 1;\n\n// The maximum code-point a four-byte UTF-8 sequence can represent.\nconstexpr uint32_t kMaxCodePoint4 = (static_cast(1) << (3 + 3*6)) - 1;\n\n// Chops off the n lowest bits from a bit pattern. Returns the n\n// lowest bits. As a side effect, the original bit pattern will be\n// shifted to the right by n bits.\ninline uint32_t ChopLowBits(uint32_t* bits, int n) {\n const uint32_t low_bits = *bits & ((static_cast(1) << n) - 1);\n *bits >>= n;\n return low_bits;\n}\n\n// Converts a Unicode code point to a narrow string in UTF-8 encoding.\n// code_point parameter is of type uint32_t because wchar_t may not be\n// wide enough to contain a code point.\n// If the code_point is not a valid Unicode code point\n// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted\n// to \"(Invalid Unicode 0xXXXXXXXX)\".\nstd::string CodePointToUtf8(uint32_t code_point) {\n if (code_point > kMaxCodePoint4) {\n return \"(Invalid Unicode 0x\" + String::FormatHexUInt32(code_point) + \")\";\n }\n\n char str[5]; // Big enough for the largest valid code point.\n if (code_point <= kMaxCodePoint1) {\n str[1] = '\\0';\n str[0] = static_cast(code_point); // 0xxxxxxx\n } else if (code_point <= kMaxCodePoint2) {\n str[2] = '\\0';\n str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx\n str[0] = static_cast(0xC0 | code_point); // 110xxxxx\n } else if (code_point <= kMaxCodePoint3) {\n str[3] = '\\0';\n str[2] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx\n str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx\n str[0] = static_cast(0xE0 | code_point); // 1110xxxx\n } else { // code_point <= kMaxCodePoint4\n str[4] = '\\0';\n str[3] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx\n str[2] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx\n str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx\n str[0] = static_cast(0xF0 | code_point); // 11110xxx\n }\n return str;\n}\n\n// The following two functions only make sense if the system\n// uses UTF-16 for wide string encoding. All supported systems\n// with 16 bit wchar_t (Windows, Cygwin) do use UTF-16.\n\n// Determines if the arguments constitute UTF-16 surrogate pair\n// and thus should be combined into a single Unicode code point\n// using CreateCodePointFromUtf16SurrogatePair.\ninline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {\n return sizeof(wchar_t) == 2 &&\n (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;\n}\n\n// Creates a Unicode code point from UTF16 surrogate pair.\ninline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first,\n wchar_t second) {\n const auto first_u = static_cast(first);\n const auto second_u = static_cast(second);\n const uint32_t mask = (1 << 10) - 1;\n return (sizeof(wchar_t) == 2)\n ? (((first_u & mask) << 10) | (second_u & mask)) + 0x10000\n :\n // This function should not be called when the condition is\n // false, but we provide a sensible default in case it is.\n first_u;\n}\n\n// Converts a wide string to a narrow string in UTF-8 encoding.\n// The wide string is assumed to have the following encoding:\n// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)\n// UTF-32 if sizeof(wchar_t) == 4 (on Linux)\n// Parameter str points to a null-terminated wide string.\n// Parameter num_chars may additionally limit the number\n// of wchar_t characters processed. -1 is used when the entire string\n// should be processed.\n// If the string contains code points that are not valid Unicode code points\n// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output\n// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding\n// and contains invalid UTF-16 surrogate pairs, values in those pairs\n// will be encoded as individual Unicode characters from Basic Normal Plane.\nstd::string WideStringToUtf8(const wchar_t* str, int num_chars) {\n if (num_chars == -1)\n num_chars = static_cast(wcslen(str));\n\n ::std::stringstream stream;\n for (int i = 0; i < num_chars; ++i) {\n uint32_t unicode_code_point;\n\n if (str[i] == L'\\0') {\n break;\n } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {\n unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],\n str[i + 1]);\n i++;\n } else {\n unicode_code_point = static_cast(str[i]);\n }\n\n stream << CodePointToUtf8(unicode_code_point);\n }\n return StringStreamToString(&stream);\n}\n\n// Converts a wide C string to an std::string using the UTF-8 encoding.\n// NULL will be converted to \"(null)\".\nstd::string String::ShowWideCString(const wchar_t * wide_c_str) {\n if (wide_c_str == nullptr) return \"(null)\";\n\n return internal::WideStringToUtf8(wide_c_str, -1);\n}\n\n// Compares two wide C strings. Returns true if and only if they have the\n// same content.\n//\n// Unlike wcscmp(), this function can handle NULL argument(s). A NULL\n// C string is considered different to any non-NULL C string,\n// including the empty string.\nbool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {\n if (lhs == nullptr) return rhs == nullptr;\n\n if (rhs == nullptr) return false;\n\n return wcscmp(lhs, rhs) == 0;\n}\n\n// Helper function for *_STREQ on wide strings.\nAssertionResult CmpHelperSTREQ(const char* lhs_expression,\n const char* rhs_expression,\n const wchar_t* lhs,\n const wchar_t* rhs) {\n if (String::WideCStringEquals(lhs, rhs)) {\n return AssertionSuccess();\n }\n\n return EqFailure(lhs_expression,\n rhs_expression,\n PrintToString(lhs),\n PrintToString(rhs),\n false);\n}\n\n// Helper function for *_STRNE on wide strings.\nAssertionResult CmpHelperSTRNE(const char* s1_expression,\n const char* s2_expression,\n const wchar_t* s1,\n const wchar_t* s2) {\n if (!String::WideCStringEquals(s1, s2)) {\n return AssertionSuccess();\n }\n\n return AssertionFailure() << \"Expected: (\" << s1_expression << \") != (\"\n << s2_expression << \"), actual: \"\n << PrintToString(s1)\n << \" vs \" << PrintToString(s2);\n}\n\n// Compares two C strings, ignoring case. Returns true if and only if they have\n// the same content.\n//\n// Unlike strcasecmp(), this function can handle NULL argument(s). A\n// NULL C string is considered different to any non-NULL C string,\n// including the empty string.\nbool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {\n if (lhs == nullptr) return rhs == nullptr;\n if (rhs == nullptr) return false;\n return posix::StrCaseCmp(lhs, rhs) == 0;\n}\n\n// Compares two wide C strings, ignoring case. Returns true if and only if they\n// have the same content.\n//\n// Unlike wcscasecmp(), this function can handle NULL argument(s).\n// A NULL C string is considered different to any non-NULL wide C string,\n// including the empty string.\n// NB: The implementations on different platforms slightly differ.\n// On windows, this method uses _wcsicmp which compares according to LC_CTYPE\n// environment variable. On GNU platform this method uses wcscasecmp\n// which compares according to LC_CTYPE category of the current locale.\n// On MacOS X, it uses towlower, which also uses LC_CTYPE category of the\n// current locale.\nbool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,\n const wchar_t* rhs) {\n if (lhs == nullptr) return rhs == nullptr;\n\n if (rhs == nullptr) return false;\n\n#if GTEST_OS_WINDOWS\n return _wcsicmp(lhs, rhs) == 0;\n#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID\n return wcscasecmp(lhs, rhs) == 0;\n#else\n // Android, Mac OS X and Cygwin don't define wcscasecmp.\n // Other unknown OSes may not define it either.\n wint_t left, right;\n do {\n left = towlower(static_cast(*lhs++));\n right = towlower(static_cast(*rhs++));\n } while (left && left == right);\n return left == right;\n#endif // OS selector\n}\n\n// Returns true if and only if str ends with the given suffix, ignoring case.\n// Any string is considered to end with an empty suffix.\nbool String::EndsWithCaseInsensitive(\n const std::string& str, const std::string& suffix) {\n const size_t str_len = str.length();\n const size_t suffix_len = suffix.length();\n return (str_len >= suffix_len) &&\n CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,\n suffix.c_str());\n}\n\n// Formats an int value as \"%02d\".\nstd::string String::FormatIntWidth2(int value) {\n return FormatIntWidthN(value, 2);\n}\n\n// Formats an int value to given width with leading zeros.\nstd::string String::FormatIntWidthN(int value, int width) {\n std::stringstream ss;\n ss << std::setfill('0') << std::setw(width) << value;\n return ss.str();\n}\n\n// Formats an int value as \"%X\".\nstd::string String::FormatHexUInt32(uint32_t value) {\n std::stringstream ss;\n ss << std::hex << std::uppercase << value;\n return ss.str();\n}\n\n// Formats an int value as \"%X\".\nstd::string String::FormatHexInt(int value) {\n return FormatHexUInt32(static_cast(value));\n}\n\n// Formats a byte as \"%02X\".\nstd::string String::FormatByte(unsigned char value) {\n std::stringstream ss;\n ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase\n << static_cast(value);\n return ss.str();\n}\n\n// Converts the buffer in a stringstream to an std::string, converting NUL\n// bytes to \"\\\\0\" along the way.\nstd::string StringStreamToString(::std::stringstream* ss) {\n const ::std::string& str = ss->str();\n const char* const start = str.c_str();\n const char* const end = start + str.length();\n\n std::string result;\n result.reserve(static_cast(2 * (end - start)));\n for (const char* ch = start; ch != end; ++ch) {\n if (*ch == '\\0') {\n result += \"\\\\0\"; // Replaces NUL with \"\\\\0\";\n } else {\n result += *ch;\n }\n }\n\n return result;\n}\n\n// Appends the user-supplied message to the Google-Test-generated message.\nstd::string AppendUserMessage(const std::string& gtest_msg,\n const Message& user_msg) {\n // Appends the user message if it's non-empty.\n const std::string user_msg_string = user_msg.GetString();\n if (user_msg_string.empty()) {\n return gtest_msg;\n }\n if (gtest_msg.empty()) {\n return user_msg_string;\n }\n return gtest_msg + \"\\n\" + user_msg_string;\n}\n\n} // namespace internal\n\n// class TestResult\n\n// Creates an empty TestResult.\nTestResult::TestResult()\n : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {}\n\n// D'tor.\nTestResult::~TestResult() {\n}\n\n// Returns the i-th test part result among all the results. i can\n// range from 0 to total_part_count() - 1. If i is not in that range,\n// aborts the program.\nconst TestPartResult& TestResult::GetTestPartResult(int i) const {\n if (i < 0 || i >= total_part_count())\n internal::posix::Abort();\n return test_part_results_.at(static_cast(i));\n}\n\n// Returns the i-th test property. i can range from 0 to\n// test_property_count() - 1. If i is not in that range, aborts the\n// program.\nconst TestProperty& TestResult::GetTestProperty(int i) const {\n if (i < 0 || i >= test_property_count())\n internal::posix::Abort();\n return test_properties_.at(static_cast(i));\n}\n\n// Clears the test part results.\nvoid TestResult::ClearTestPartResults() {\n test_part_results_.clear();\n}\n\n// Adds a test part result to the list.\nvoid TestResult::AddTestPartResult(const TestPartResult& test_part_result) {\n test_part_results_.push_back(test_part_result);\n}\n\n// Adds a test property to the list. If a property with the same key as the\n// supplied property is already represented, the value of this test_property\n// replaces the old value for that key.\nvoid TestResult::RecordProperty(const std::string& xml_element,\n const TestProperty& test_property) {\n if (!ValidateTestProperty(xml_element, test_property)) {\n return;\n }\n internal::MutexLock lock(&test_properties_mutex_);\n const std::vector::iterator property_with_matching_key =\n std::find_if(test_properties_.begin(), test_properties_.end(),\n internal::TestPropertyKeyIs(test_property.key()));\n if (property_with_matching_key == test_properties_.end()) {\n test_properties_.push_back(test_property);\n return;\n }\n property_with_matching_key->SetValue(test_property.value());\n}\n\n// The list of reserved attributes used in the element of XML\n// output.\nstatic const char* const kReservedTestSuitesAttributes[] = {\n \"disabled\",\n \"errors\",\n \"failures\",\n \"name\",\n \"random_seed\",\n \"tests\",\n \"time\",\n \"timestamp\"\n};\n\n// The list of reserved attributes used in the element of XML\n// output.\nstatic const char* const kReservedTestSuiteAttributes[] = {\n \"disabled\", \"errors\", \"failures\", \"name\",\n \"tests\", \"time\", \"timestamp\", \"skipped\"};\n\n// The list of reserved attributes used in the element of XML output.\nstatic const char* const kReservedTestCaseAttributes[] = {\n \"classname\", \"name\", \"status\", \"time\", \"type_param\",\n \"value_param\", \"file\", \"line\"};\n\n// Use a slightly different set for allowed output to ensure existing tests can\n// still RecordProperty(\"result\") or \"RecordProperty(timestamp\")\nstatic const char* const kReservedOutputTestCaseAttributes[] = {\n \"classname\", \"name\", \"status\", \"time\", \"type_param\",\n \"value_param\", \"file\", \"line\", \"result\", \"timestamp\"};\n\ntemplate \nstd::vector ArrayAsVector(const char* const (&array)[kSize]) {\n return std::vector(array, array + kSize);\n}\n\nstatic std::vector GetReservedAttributesForElement(\n const std::string& xml_element) {\n if (xml_element == \"testsuites\") {\n return ArrayAsVector(kReservedTestSuitesAttributes);\n } else if (xml_element == \"testsuite\") {\n return ArrayAsVector(kReservedTestSuiteAttributes);\n } else if (xml_element == \"testcase\") {\n return ArrayAsVector(kReservedTestCaseAttributes);\n } else {\n GTEST_CHECK_(false) << \"Unrecognized xml_element provided: \" << xml_element;\n }\n // This code is unreachable but some compilers may not realizes that.\n return std::vector();\n}\n\n// TODO(jdesprez): Merge the two getReserved attributes once skip is improved\nstatic std::vector GetReservedOutputAttributesForElement(\n const std::string& xml_element) {\n if (xml_element == \"testsuites\") {\n return ArrayAsVector(kReservedTestSuitesAttributes);\n } else if (xml_element == \"testsuite\") {\n return ArrayAsVector(kReservedTestSuiteAttributes);\n } else if (xml_element == \"testcase\") {\n return ArrayAsVector(kReservedOutputTestCaseAttributes);\n } else {\n GTEST_CHECK_(false) << \"Unrecognized xml_element provided: \" << xml_element;\n }\n // This code is unreachable but some compilers may not realizes that.\n return std::vector();\n}\n\nstatic std::string FormatWordList(const std::vector& words) {\n Message word_list;\n for (size_t i = 0; i < words.size(); ++i) {\n if (i > 0 && words.size() > 2) {\n word_list << \", \";\n }\n if (i == words.size() - 1) {\n word_list << \"and \";\n }\n word_list << \"'\" << words[i] << \"'\";\n }\n return word_list.GetString();\n}\n\nstatic bool ValidateTestPropertyName(\n const std::string& property_name,\n const std::vector& reserved_names) {\n if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=\n reserved_names.end()) {\n ADD_FAILURE() << \"Reserved key used in RecordProperty(): \" << property_name\n << \" (\" << FormatWordList(reserved_names)\n << \" are reserved by \" << GTEST_NAME_ << \")\";\n return false;\n }\n return true;\n}\n\n// Adds a failure if the key is a reserved attribute of the element named\n// xml_element. Returns true if the property is valid.\nbool TestResult::ValidateTestProperty(const std::string& xml_element,\n const TestProperty& test_property) {\n return ValidateTestPropertyName(test_property.key(),\n GetReservedAttributesForElement(xml_element));\n}\n\n// Clears the object.\nvoid TestResult::Clear() {\n test_part_results_.clear();\n test_properties_.clear();\n death_test_count_ = 0;\n elapsed_time_ = 0;\n}\n\n// Returns true off the test part was skipped.\nstatic bool TestPartSkipped(const TestPartResult& result) {\n return result.skipped();\n}\n\n// Returns true if and only if the test was skipped.\nbool TestResult::Skipped() const {\n return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0;\n}\n\n// Returns true if and only if the test failed.\nbool TestResult::Failed() const {\n for (int i = 0; i < total_part_count(); ++i) {\n if (GetTestPartResult(i).failed())\n return true;\n }\n return false;\n}\n\n// Returns true if and only if the test part fatally failed.\nstatic bool TestPartFatallyFailed(const TestPartResult& result) {\n return result.fatally_failed();\n}\n\n// Returns true if and only if the test fatally failed.\nbool TestResult::HasFatalFailure() const {\n return CountIf(test_part_results_, TestPartFatallyFailed) > 0;\n}\n\n// Returns true if and only if the test part non-fatally failed.\nstatic bool TestPartNonfatallyFailed(const TestPartResult& result) {\n return result.nonfatally_failed();\n}\n\n// Returns true if and only if the test has a non-fatal failure.\nbool TestResult::HasNonfatalFailure() const {\n return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;\n}\n\n// Gets the number of all test parts. This is the sum of the number\n// of successful test parts and the number of failed test parts.\nint TestResult::total_part_count() const {\n return static_cast(test_part_results_.size());\n}\n\n// Returns the number of the test properties.\nint TestResult::test_property_count() const {\n return static_cast(test_properties_.size());\n}\n\n// class Test\n\n// Creates a Test object.\n\n// The c'tor saves the states of all flags.\nTest::Test()\n : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {\n}\n\n// The d'tor restores the states of all flags. The actual work is\n// done by the d'tor of the gtest_flag_saver_ field, and thus not\n// visible here.\nTest::~Test() {\n}\n\n// Sets up the test fixture.\n//\n// A sub-class may override this.\nvoid Test::SetUp() {\n}\n\n// Tears down the test fixture.\n//\n// A sub-class may override this.\nvoid Test::TearDown() {\n}\n\n// Allows user supplied key value pairs to be recorded for later output.\nvoid Test::RecordProperty(const std::string& key, const std::string& value) {\n UnitTest::GetInstance()->RecordProperty(key, value);\n}\n\n// Allows user supplied key value pairs to be recorded for later output.\nvoid Test::RecordProperty(const std::string& key, int value) {\n Message value_message;\n value_message << value;\n RecordProperty(key, value_message.GetString().c_str());\n}\n\nnamespace internal {\n\nvoid ReportFailureInUnknownLocation(TestPartResult::Type result_type,\n const std::string& message) {\n // This function is a friend of UnitTest and as such has access to\n // AddTestPartResult.\n UnitTest::GetInstance()->AddTestPartResult(\n result_type,\n nullptr, // No info about the source file where the exception occurred.\n -1, // We have no info on which line caused the exception.\n message,\n \"\"); // No stack trace, either.\n}\n\n} // namespace internal\n\n// Google Test requires all tests in the same test suite to use the same test\n// fixture class. This function checks if the current test has the\n// same fixture class as the first test in the current test suite. If\n// yes, it returns true; otherwise it generates a Google Test failure and\n// returns false.\nbool Test::HasSameFixtureClass() {\n internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n const TestSuite* const test_suite = impl->current_test_suite();\n\n // Info about the first test in the current test suite.\n const TestInfo* const first_test_info = test_suite->test_info_list()[0];\n const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;\n const char* const first_test_name = first_test_info->name();\n\n // Info about the current test.\n const TestInfo* const this_test_info = impl->current_test_info();\n const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;\n const char* const this_test_name = this_test_info->name();\n\n if (this_fixture_id != first_fixture_id) {\n // Is the first test defined using TEST?\n const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();\n // Is this test defined using TEST?\n const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();\n\n if (first_is_TEST || this_is_TEST) {\n // Both TEST and TEST_F appear in same test suite, which is incorrect.\n // Tell the user how to fix this.\n\n // Gets the name of the TEST and the name of the TEST_F. Note\n // that first_is_TEST and this_is_TEST cannot both be true, as\n // the fixture IDs are different for the two tests.\n const char* const TEST_name =\n first_is_TEST ? first_test_name : this_test_name;\n const char* const TEST_F_name =\n first_is_TEST ? this_test_name : first_test_name;\n\n ADD_FAILURE()\n << \"All tests in the same test suite must use the same test fixture\\n\"\n << \"class, so mixing TEST_F and TEST in the same test suite is\\n\"\n << \"illegal. In test suite \" << this_test_info->test_suite_name()\n << \",\\n\"\n << \"test \" << TEST_F_name << \" is defined using TEST_F but\\n\"\n << \"test \" << TEST_name << \" is defined using TEST. You probably\\n\"\n << \"want to change the TEST to TEST_F or move it to another test\\n\"\n << \"case.\";\n } else {\n // Two fixture classes with the same name appear in two different\n // namespaces, which is not allowed. Tell the user how to fix this.\n ADD_FAILURE()\n << \"All tests in the same test suite must use the same test fixture\\n\"\n << \"class. However, in test suite \"\n << this_test_info->test_suite_name() << \",\\n\"\n << \"you defined test \" << first_test_name << \" and test \"\n << this_test_name << \"\\n\"\n << \"using two different test fixture classes. This can happen if\\n\"\n << \"the two classes are from different namespaces or translation\\n\"\n << \"units and have the same name. You should probably rename one\\n\"\n << \"of the classes to put the tests into different test suites.\";\n }\n return false;\n }\n\n return true;\n}\n\n#if GTEST_HAS_SEH\n\n// Adds an \"exception thrown\" fatal failure to the current test. This\n// function returns its result via an output parameter pointer because VC++\n// prohibits creation of objects with destructors on stack in functions\n// using __try (see error C2712).\nstatic std::string* FormatSehExceptionMessage(DWORD exception_code,\n const char* location) {\n Message message;\n message << \"SEH exception with code 0x\" << std::setbase(16) <<\n exception_code << std::setbase(10) << \" thrown in \" << location << \".\";\n\n return new std::string(message.GetString());\n}\n\n#endif // GTEST_HAS_SEH\n\nnamespace internal {\n\n#if GTEST_HAS_EXCEPTIONS\n\n// Adds an \"exception thrown\" fatal failure to the current test.\nstatic std::string FormatCxxExceptionMessage(const char* description,\n const char* location) {\n Message message;\n if (description != nullptr) {\n message << \"C++ exception with description \\\"\" << description << \"\\\"\";\n } else {\n message << \"Unknown C++ exception\";\n }\n message << \" thrown in \" << location << \".\";\n\n return message.GetString();\n}\n\nstatic std::string PrintTestPartResultToString(\n const TestPartResult& test_part_result);\n\nGoogleTestFailureException::GoogleTestFailureException(\n const TestPartResult& failure)\n : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}\n\n#endif // GTEST_HAS_EXCEPTIONS\n\n// We put these helper functions in the internal namespace as IBM's xlC\n// compiler rejects the code if they were declared static.\n\n// Runs the given method and handles SEH exceptions it throws, when\n// SEH is supported; returns the 0-value for type Result in case of an\n// SEH exception. (Microsoft compilers cannot handle SEH and C++\n// exceptions in the same function. Therefore, we provide a separate\n// wrapper function for handling SEH exceptions.)\ntemplate \nResult HandleSehExceptionsInMethodIfSupported(\n T* object, Result (T::*method)(), const char* location) {\n#if GTEST_HAS_SEH\n __try {\n return (object->*method)();\n } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT\n GetExceptionCode())) {\n // We create the exception message on the heap because VC++ prohibits\n // creation of objects with destructors on stack in functions using __try\n // (see error C2712).\n std::string* exception_message = FormatSehExceptionMessage(\n GetExceptionCode(), location);\n internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,\n *exception_message);\n delete exception_message;\n return static_cast(0);\n }\n#else\n (void)location;\n return (object->*method)();\n#endif // GTEST_HAS_SEH\n}\n\n// Runs the given method and catches and reports C++ and/or SEH-style\n// exceptions, if they are supported; returns the 0-value for type\n// Result in case of an SEH exception.\ntemplate \nResult HandleExceptionsInMethodIfSupported(\n T* object, Result (T::*method)(), const char* location) {\n // NOTE: The user code can affect the way in which Google Test handles\n // exceptions by setting GTEST_FLAG(catch_exceptions), but only before\n // RUN_ALL_TESTS() starts. It is technically possible to check the flag\n // after the exception is caught and either report or re-throw the\n // exception based on the flag's value:\n //\n // try {\n // // Perform the test method.\n // } catch (...) {\n // if (GTEST_FLAG(catch_exceptions))\n // // Report the exception as failure.\n // else\n // throw; // Re-throws the original exception.\n // }\n //\n // However, the purpose of this flag is to allow the program to drop into\n // the debugger when the exception is thrown. On most platforms, once the\n // control enters the catch block, the exception origin information is\n // lost and the debugger will stop the program at the point of the\n // re-throw in this function -- instead of at the point of the original\n // throw statement in the code under test. For this reason, we perform\n // the check early, sacrificing the ability to affect Google Test's\n // exception handling in the method where the exception is thrown.\n if (internal::GetUnitTestImpl()->catch_exceptions()) {\n#if GTEST_HAS_EXCEPTIONS\n try {\n return HandleSehExceptionsInMethodIfSupported(object, method, location);\n } catch (const AssertionException&) { // NOLINT\n // This failure was reported already.\n } catch (const internal::GoogleTestFailureException&) { // NOLINT\n // This exception type can only be thrown by a failed Google\n // Test assertion with the intention of letting another testing\n // framework catch it. Therefore we just re-throw it.\n throw;\n } catch (const std::exception& e) { // NOLINT\n internal::ReportFailureInUnknownLocation(\n TestPartResult::kFatalFailure,\n FormatCxxExceptionMessage(e.what(), location));\n } catch (...) { // NOLINT\n internal::ReportFailureInUnknownLocation(\n TestPartResult::kFatalFailure,\n FormatCxxExceptionMessage(nullptr, location));\n }\n return static_cast(0);\n#else\n return HandleSehExceptionsInMethodIfSupported(object, method, location);\n#endif // GTEST_HAS_EXCEPTIONS\n } else {\n return (object->*method)();\n }\n}\n\n} // namespace internal\n\n// Runs the test and updates the test result.\nvoid Test::Run() {\n if (!HasSameFixtureClass()) return;\n\n internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n impl->os_stack_trace_getter()->UponLeavingGTest();\n internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, \"SetUp()\");\n // We will run the test only if SetUp() was successful and didn't call\n // GTEST_SKIP().\n if (!HasFatalFailure() && !IsSkipped()) {\n impl->os_stack_trace_getter()->UponLeavingGTest();\n internal::HandleExceptionsInMethodIfSupported(\n this, &Test::TestBody, \"the test body\");\n }\n\n // However, we want to clean up as much as possible. Hence we will\n // always call TearDown(), even if SetUp() or the test body has\n // failed.\n impl->os_stack_trace_getter()->UponLeavingGTest();\n internal::HandleExceptionsInMethodIfSupported(\n this, &Test::TearDown, \"TearDown()\");\n}\n\n// Returns true if and only if the current test has a fatal failure.\nbool Test::HasFatalFailure() {\n return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();\n}\n\n// Returns true if and only if the current test has a non-fatal failure.\nbool Test::HasNonfatalFailure() {\n return internal::GetUnitTestImpl()->current_test_result()->\n HasNonfatalFailure();\n}\n\n// Returns true if and only if the current test was skipped.\nbool Test::IsSkipped() {\n return internal::GetUnitTestImpl()->current_test_result()->Skipped();\n}\n\n// class TestInfo\n\n// Constructs a TestInfo object. It assumes ownership of the test factory\n// object.\nTestInfo::TestInfo(const std::string& a_test_suite_name,\n const std::string& a_name, const char* a_type_param,\n const char* a_value_param,\n internal::CodeLocation a_code_location,\n internal::TypeId fixture_class_id,\n internal::TestFactoryBase* factory)\n : test_suite_name_(a_test_suite_name),\n name_(a_name),\n type_param_(a_type_param ? new std::string(a_type_param) : nullptr),\n value_param_(a_value_param ? new std::string(a_value_param) : nullptr),\n location_(a_code_location),\n fixture_class_id_(fixture_class_id),\n should_run_(false),\n is_disabled_(false),\n matches_filter_(false),\n is_in_another_shard_(false),\n factory_(factory),\n result_() {}\n\n// Destructs a TestInfo object.\nTestInfo::~TestInfo() { delete factory_; }\n\nnamespace internal {\n\n// Creates a new TestInfo object and registers it with Google Test;\n// returns the created object.\n//\n// Arguments:\n//\n// test_suite_name: name of the test suite\n// name: name of the test\n// type_param: the name of the test's type parameter, or NULL if\n// this is not a typed or a type-parameterized test.\n// value_param: text representation of the test's value parameter,\n// or NULL if this is not a value-parameterized test.\n// code_location: code location where the test is defined\n// fixture_class_id: ID of the test fixture class\n// set_up_tc: pointer to the function that sets up the test suite\n// tear_down_tc: pointer to the function that tears down the test suite\n// factory: pointer to the factory that creates a test object.\n// The newly created TestInfo instance will assume\n// ownership of the factory object.\nTestInfo* MakeAndRegisterTestInfo(\n const char* test_suite_name, const char* name, const char* type_param,\n const char* value_param, CodeLocation code_location,\n TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,\n TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) {\n TestInfo* const test_info =\n new TestInfo(test_suite_name, name, type_param, value_param,\n code_location, fixture_class_id, factory);\n GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);\n return test_info;\n}\n\nvoid ReportInvalidTestSuiteType(const char* test_suite_name,\n CodeLocation code_location) {\n Message errors;\n errors\n << \"Attempted redefinition of test suite \" << test_suite_name << \".\\n\"\n << \"All tests in the same test suite must use the same test fixture\\n\"\n << \"class. However, in test suite \" << test_suite_name << \", you tried\\n\"\n << \"to define a test using a fixture class different from the one\\n\"\n << \"used earlier. This can happen if the two fixture classes are\\n\"\n << \"from different namespaces and have the same name. You should\\n\"\n << \"probably rename one of the classes to put the tests into different\\n\"\n << \"test suites.\";\n\n GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),\n code_location.line)\n << \" \" << errors.GetString();\n}\n} // namespace internal\n\nnamespace {\n\n// A predicate that checks the test name of a TestInfo against a known\n// value.\n//\n// This is used for implementation of the TestSuite class only. We put\n// it in the anonymous namespace to prevent polluting the outer\n// namespace.\n//\n// TestNameIs is copyable.\nclass TestNameIs {\n public:\n // Constructor.\n //\n // TestNameIs has NO default constructor.\n explicit TestNameIs(const char* name)\n : name_(name) {}\n\n // Returns true if and only if the test name of test_info matches name_.\n bool operator()(const TestInfo * test_info) const {\n return test_info && test_info->name() == name_;\n }\n\n private:\n std::string name_;\n};\n\n} // namespace\n\nnamespace internal {\n\n// This method expands all parameterized tests registered with macros TEST_P\n// and INSTANTIATE_TEST_SUITE_P into regular tests and registers those.\n// This will be done just once during the program runtime.\nvoid UnitTestImpl::RegisterParameterizedTests() {\n if (!parameterized_tests_registered_) {\n parameterized_test_registry_.RegisterTests();\n type_parameterized_test_registry_.CheckForInstantiations();\n parameterized_tests_registered_ = true;\n }\n}\n\n} // namespace internal\n\n// Creates the test object, runs it, records its result, and then\n// deletes it.\nvoid TestInfo::Run() {\n if (!should_run_) return;\n\n // Tells UnitTest where to store test result.\n internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n impl->set_current_test_info(this);\n\n TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();\n\n // Notifies the unit test event listeners that a test is about to start.\n repeater->OnTestStart(*this);\n\n result_.set_start_timestamp(internal::GetTimeInMillis());\n internal::Timer timer;\n\n impl->os_stack_trace_getter()->UponLeavingGTest();\n\n // Creates the test object.\n Test* const test = internal::HandleExceptionsInMethodIfSupported(\n factory_, &internal::TestFactoryBase::CreateTest,\n \"the test fixture's constructor\");\n\n // Runs the test if the constructor didn't generate a fatal failure or invoke\n // GTEST_SKIP().\n // Note that the object will not be null\n if (!Test::HasFatalFailure() && !Test::IsSkipped()) {\n // This doesn't throw as all user code that can throw are wrapped into\n // exception handling code.\n test->Run();\n }\n\n if (test != nullptr) {\n // Deletes the test object.\n impl->os_stack_trace_getter()->UponLeavingGTest();\n internal::HandleExceptionsInMethodIfSupported(\n test, &Test::DeleteSelf_, \"the test fixture's destructor\");\n }\n\n result_.set_elapsed_time(timer.Elapsed());\n\n // Notifies the unit test event listener that a test has just finished.\n repeater->OnTestEnd(*this);\n\n // Tells UnitTest to stop associating assertion results to this\n // test.\n impl->set_current_test_info(nullptr);\n}\n\n// Skip and records a skipped test result for this object.\nvoid TestInfo::Skip() {\n if (!should_run_) return;\n\n internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n impl->set_current_test_info(this);\n\n TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();\n\n // Notifies the unit test event listeners that a test is about to start.\n repeater->OnTestStart(*this);\n\n const TestPartResult test_part_result =\n TestPartResult(TestPartResult::kSkip, this->file(), this->line(), \"\");\n impl->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(\n test_part_result);\n\n // Notifies the unit test event listener that a test has just finished.\n repeater->OnTestEnd(*this);\n impl->set_current_test_info(nullptr);\n}\n\n// class TestSuite\n\n// Gets the number of successful tests in this test suite.\nint TestSuite::successful_test_count() const {\n return CountIf(test_info_list_, TestPassed);\n}\n\n// Gets the number of successful tests in this test suite.\nint TestSuite::skipped_test_count() const {\n return CountIf(test_info_list_, TestSkipped);\n}\n\n// Gets the number of failed tests in this test suite.\nint TestSuite::failed_test_count() const {\n return CountIf(test_info_list_, TestFailed);\n}\n\n// Gets the number of disabled tests that will be reported in the XML report.\nint TestSuite::reportable_disabled_test_count() const {\n return CountIf(test_info_list_, TestReportableDisabled);\n}\n\n// Gets the number of disabled tests in this test suite.\nint TestSuite::disabled_test_count() const {\n return CountIf(test_info_list_, TestDisabled);\n}\n\n// Gets the number of tests to be printed in the XML report.\nint TestSuite::reportable_test_count() const {\n return CountIf(test_info_list_, TestReportable);\n}\n\n// Get the number of tests in this test suite that should run.\nint TestSuite::test_to_run_count() const {\n return CountIf(test_info_list_, ShouldRunTest);\n}\n\n// Gets the number of all tests.\nint TestSuite::total_test_count() const {\n return static_cast(test_info_list_.size());\n}\n\n// Creates a TestSuite with the given name.\n//\n// Arguments:\n//\n// a_name: name of the test suite\n// a_type_param: the name of the test suite's type parameter, or NULL if\n// this is not a typed or a type-parameterized test suite.\n// set_up_tc: pointer to the function that sets up the test suite\n// tear_down_tc: pointer to the function that tears down the test suite\nTestSuite::TestSuite(const char* a_name, const char* a_type_param,\n internal::SetUpTestSuiteFunc set_up_tc,\n internal::TearDownTestSuiteFunc tear_down_tc)\n : name_(a_name),\n type_param_(a_type_param ? new std::string(a_type_param) : nullptr),\n set_up_tc_(set_up_tc),\n tear_down_tc_(tear_down_tc),\n should_run_(false),\n start_timestamp_(0),\n elapsed_time_(0) {}\n\n// Destructor of TestSuite.\nTestSuite::~TestSuite() {\n // Deletes every Test in the collection.\n ForEach(test_info_list_, internal::Delete);\n}\n\n// Returns the i-th test among all the tests. i can range from 0 to\n// total_test_count() - 1. If i is not in that range, returns NULL.\nconst TestInfo* TestSuite::GetTestInfo(int i) const {\n const int index = GetElementOr(test_indices_, i, -1);\n return index < 0 ? nullptr : test_info_list_[static_cast(index)];\n}\n\n// Returns the i-th test among all the tests. i can range from 0 to\n// total_test_count() - 1. If i is not in that range, returns NULL.\nTestInfo* TestSuite::GetMutableTestInfo(int i) {\n const int index = GetElementOr(test_indices_, i, -1);\n return index < 0 ? nullptr : test_info_list_[static_cast(index)];\n}\n\n// Adds a test to this test suite. Will delete the test upon\n// destruction of the TestSuite object.\nvoid TestSuite::AddTestInfo(TestInfo* test_info) {\n test_info_list_.push_back(test_info);\n test_indices_.push_back(static_cast(test_indices_.size()));\n}\n\n// Runs every test in this TestSuite.\nvoid TestSuite::Run() {\n if (!should_run_) return;\n\n internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n impl->set_current_test_suite(this);\n\n TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();\n\n // Call both legacy and the new API\n repeater->OnTestSuiteStart(*this);\n// Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n repeater->OnTestCaseStart(*this);\n#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n impl->os_stack_trace_getter()->UponLeavingGTest();\n internal::HandleExceptionsInMethodIfSupported(\n this, &TestSuite::RunSetUpTestSuite, \"SetUpTestSuite()\");\n\n start_timestamp_ = internal::GetTimeInMillis();\n internal::Timer timer;\n for (int i = 0; i < total_test_count(); i++) {\n GetMutableTestInfo(i)->Run();\n if (GTEST_FLAG(fail_fast) && GetMutableTestInfo(i)->result()->Failed()) {\n for (int j = i + 1; j < total_test_count(); j++) {\n GetMutableTestInfo(j)->Skip();\n }\n break;\n }\n }\n elapsed_time_ = timer.Elapsed();\n\n impl->os_stack_trace_getter()->UponLeavingGTest();\n internal::HandleExceptionsInMethodIfSupported(\n this, &TestSuite::RunTearDownTestSuite, \"TearDownTestSuite()\");\n\n // Call both legacy and the new API\n repeater->OnTestSuiteEnd(*this);\n// Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n repeater->OnTestCaseEnd(*this);\n#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n impl->set_current_test_suite(nullptr);\n}\n\n// Skips all tests under this TestSuite.\nvoid TestSuite::Skip() {\n if (!should_run_) return;\n\n internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n impl->set_current_test_suite(this);\n\n TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();\n\n // Call both legacy and the new API\n repeater->OnTestSuiteStart(*this);\n// Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n repeater->OnTestCaseStart(*this);\n#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n for (int i = 0; i < total_test_count(); i++) {\n GetMutableTestInfo(i)->Skip();\n }\n\n // Call both legacy and the new API\n repeater->OnTestSuiteEnd(*this);\n // Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n repeater->OnTestCaseEnd(*this);\n#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n impl->set_current_test_suite(nullptr);\n}\n\n// Clears the results of all tests in this test suite.\nvoid TestSuite::ClearResult() {\n ad_hoc_test_result_.Clear();\n ForEach(test_info_list_, TestInfo::ClearTestResult);\n}\n\n// Shuffles the tests in this test suite.\nvoid TestSuite::ShuffleTests(internal::Random* random) {\n Shuffle(random, &test_indices_);\n}\n\n// Restores the test order to before the first shuffle.\nvoid TestSuite::UnshuffleTests() {\n for (size_t i = 0; i < test_indices_.size(); i++) {\n test_indices_[i] = static_cast(i);\n }\n}\n\n// Formats a countable noun. Depending on its quantity, either the\n// singular form or the plural form is used. e.g.\n//\n// FormatCountableNoun(1, \"formula\", \"formuli\") returns \"1 formula\".\n// FormatCountableNoun(5, \"book\", \"books\") returns \"5 books\".\nstatic std::string FormatCountableNoun(int count,\n const char * singular_form,\n const char * plural_form) {\n return internal::StreamableToString(count) + \" \" +\n (count == 1 ? singular_form : plural_form);\n}\n\n// Formats the count of tests.\nstatic std::string FormatTestCount(int test_count) {\n return FormatCountableNoun(test_count, \"test\", \"tests\");\n}\n\n// Formats the count of test suites.\nstatic std::string FormatTestSuiteCount(int test_suite_count) {\n return FormatCountableNoun(test_suite_count, \"test suite\", \"test suites\");\n}\n\n// Converts a TestPartResult::Type enum to human-friendly string\n// representation. Both kNonFatalFailure and kFatalFailure are translated\n// to \"Failure\", as the user usually doesn't care about the difference\n// between the two when viewing the test result.\nstatic const char * TestPartResultTypeToString(TestPartResult::Type type) {\n switch (type) {\n case TestPartResult::kSkip:\n return \"Skipped\\n\";\n case TestPartResult::kSuccess:\n return \"Success\";\n\n case TestPartResult::kNonFatalFailure:\n case TestPartResult::kFatalFailure:\n#ifdef _MSC_VER\n return \"error: \";\n#else\n return \"Failure\\n\";\n#endif\n default:\n return \"Unknown result type\";\n }\n}\n\nnamespace internal {\nnamespace {\nenum class GTestColor { kDefault, kRed, kGreen, kYellow };\n} // namespace\n\n// Prints a TestPartResult to an std::string.\nstatic std::string PrintTestPartResultToString(\n const TestPartResult& test_part_result) {\n return (Message()\n << internal::FormatFileLocation(test_part_result.file_name(),\n test_part_result.line_number())\n << \" \" << TestPartResultTypeToString(test_part_result.type())\n << test_part_result.message()).GetString();\n}\n\n// Prints a TestPartResult.\nstatic void PrintTestPartResult(const TestPartResult& test_part_result) {\n const std::string& result =\n PrintTestPartResultToString(test_part_result);\n printf(\"%s\\n\", result.c_str());\n fflush(stdout);\n // If the test program runs in Visual Studio or a debugger, the\n // following statements add the test part result message to the Output\n // window such that the user can double-click on it to jump to the\n // corresponding source code location; otherwise they do nothing.\n#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE\n // We don't call OutputDebugString*() on Windows Mobile, as printing\n // to stdout is done by OutputDebugString() there already - we don't\n // want the same message printed twice.\n ::OutputDebugStringA(result.c_str());\n ::OutputDebugStringA(\"\\n\");\n#endif\n}\n\n// class PrettyUnitTestResultPrinter\n#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \\\n !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW\n\n// Returns the character attribute for the given color.\nstatic WORD GetColorAttribute(GTestColor color) {\n switch (color) {\n case GTestColor::kRed:\n return FOREGROUND_RED;\n case GTestColor::kGreen:\n return FOREGROUND_GREEN;\n case GTestColor::kYellow:\n return FOREGROUND_RED | FOREGROUND_GREEN;\n default: return 0;\n }\n}\n\nstatic int GetBitOffset(WORD color_mask) {\n if (color_mask == 0) return 0;\n\n int bitOffset = 0;\n while ((color_mask & 1) == 0) {\n color_mask >>= 1;\n ++bitOffset;\n }\n return bitOffset;\n}\n\nstatic WORD GetNewColor(GTestColor color, WORD old_color_attrs) {\n // Let's reuse the BG\n static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |\n BACKGROUND_RED | BACKGROUND_INTENSITY;\n static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |\n FOREGROUND_RED | FOREGROUND_INTENSITY;\n const WORD existing_bg = old_color_attrs & background_mask;\n\n WORD new_color =\n GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;\n static const int bg_bitOffset = GetBitOffset(background_mask);\n static const int fg_bitOffset = GetBitOffset(foreground_mask);\n\n if (((new_color & background_mask) >> bg_bitOffset) ==\n ((new_color & foreground_mask) >> fg_bitOffset)) {\n new_color ^= FOREGROUND_INTENSITY; // invert intensity\n }\n return new_color;\n}\n\n#else\n\n// Returns the ANSI color code for the given color. GTestColor::kDefault is\n// an invalid input.\nstatic const char* GetAnsiColorCode(GTestColor color) {\n switch (color) {\n case GTestColor::kRed:\n return \"1\";\n case GTestColor::kGreen:\n return \"2\";\n case GTestColor::kYellow:\n return \"3\";\n default:\n return nullptr;\n }\n}\n\n#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE\n\n// Returns true if and only if Google Test should use colors in the output.\nbool ShouldUseColor(bool stdout_is_tty) {\n const char* const gtest_color = GTEST_FLAG(color).c_str();\n\n if (String::CaseInsensitiveCStringEquals(gtest_color, \"auto\")) {\n#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW\n // On Windows the TERM variable is usually not set, but the\n // console there does support colors.\n return stdout_is_tty;\n#else\n // On non-Windows platforms, we rely on the TERM variable.\n const char* const term = posix::GetEnv(\"TERM\");\n const bool term_supports_color =\n String::CStringEquals(term, \"xterm\") ||\n String::CStringEquals(term, \"xterm-color\") ||\n String::CStringEquals(term, \"xterm-256color\") ||\n String::CStringEquals(term, \"screen\") ||\n String::CStringEquals(term, \"screen-256color\") ||\n String::CStringEquals(term, \"tmux\") ||\n String::CStringEquals(term, \"tmux-256color\") ||\n String::CStringEquals(term, \"rxvt-unicode\") ||\n String::CStringEquals(term, \"rxvt-unicode-256color\") ||\n String::CStringEquals(term, \"linux\") ||\n String::CStringEquals(term, \"cygwin\");\n return stdout_is_tty && term_supports_color;\n#endif // GTEST_OS_WINDOWS\n }\n\n return String::CaseInsensitiveCStringEquals(gtest_color, \"yes\") ||\n String::CaseInsensitiveCStringEquals(gtest_color, \"true\") ||\n String::CaseInsensitiveCStringEquals(gtest_color, \"t\") ||\n String::CStringEquals(gtest_color, \"1\");\n // We take \"yes\", \"true\", \"t\", and \"1\" as meaning \"yes\". If the\n // value is neither one of these nor \"auto\", we treat it as \"no\" to\n // be conservative.\n}\n\n// Helpers for printing colored strings to stdout. Note that on Windows, we\n// cannot simply emit special characters and have the terminal change colors.\n// This routine must actually emit the characters rather than return a string\n// that would be colored when printed, as can be done on Linux.\n\nGTEST_ATTRIBUTE_PRINTF_(2, 3)\nstatic void ColoredPrintf(GTestColor color, const char *fmt, ...) {\n va_list args;\n va_start(args, fmt);\n\n#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \\\n GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || defined(ESP_PLATFORM)\n const bool use_color = AlwaysFalse();\n#else\n static const bool in_color_mode =\n ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);\n const bool use_color = in_color_mode && (color != GTestColor::kDefault);\n#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS\n\n if (!use_color) {\n vprintf(fmt, args);\n va_end(args);\n return;\n }\n\n#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \\\n !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW\n const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);\n\n // Gets the current text color.\n CONSOLE_SCREEN_BUFFER_INFO buffer_info;\n GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);\n const WORD old_color_attrs = buffer_info.wAttributes;\n const WORD new_color = GetNewColor(color, old_color_attrs);\n\n // We need to flush the stream buffers into the console before each\n // SetConsoleTextAttribute call lest it affect the text that is already\n // printed but has not yet reached the console.\n fflush(stdout);\n SetConsoleTextAttribute(stdout_handle, new_color);\n\n vprintf(fmt, args);\n\n fflush(stdout);\n // Restores the text color.\n SetConsoleTextAttribute(stdout_handle, old_color_attrs);\n#else\n printf(\"\\033[0;3%sm\", GetAnsiColorCode(color));\n vprintf(fmt, args);\n printf(\"\\033[m\"); // Resets the terminal to default.\n#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE\n va_end(args);\n}\n\n// Text printed in Google Test's text output and --gtest_list_tests\n// output to label the type parameter and value parameter for a test.\nstatic const char kTypeParamLabel[] = \"TypeParam\";\nstatic const char kValueParamLabel[] = \"GetParam()\";\n\nstatic void PrintFullTestCommentIfPresent(const TestInfo& test_info) {\n const char* const type_param = test_info.type_param();\n const char* const value_param = test_info.value_param();\n\n if (type_param != nullptr || value_param != nullptr) {\n printf(\", where \");\n if (type_param != nullptr) {\n printf(\"%s = %s\", kTypeParamLabel, type_param);\n if (value_param != nullptr) printf(\" and \");\n }\n if (value_param != nullptr) {\n printf(\"%s = %s\", kValueParamLabel, value_param);\n }\n }\n}\n\n// This class implements the TestEventListener interface.\n//\n// Class PrettyUnitTestResultPrinter is copyable.\nclass PrettyUnitTestResultPrinter : public TestEventListener {\n public:\n PrettyUnitTestResultPrinter() {}\n static void PrintTestName(const char* test_suite, const char* test) {\n printf(\"%s.%s\", test_suite, test);\n }\n\n // The following methods override what's in the TestEventListener class.\n void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}\n void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;\n void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;\n void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n void OnTestCaseStart(const TestCase& test_case) override;\n#else\n void OnTestSuiteStart(const TestSuite& test_suite) override;\n#endif // OnTestCaseStart\n\n void OnTestStart(const TestInfo& test_info) override;\n\n void OnTestPartResult(const TestPartResult& result) override;\n void OnTestEnd(const TestInfo& test_info) override;\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n void OnTestCaseEnd(const TestCase& test_case) override;\n#else\n void OnTestSuiteEnd(const TestSuite& test_suite) override;\n#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;\n void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}\n void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;\n void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}\n\n private:\n static void PrintFailedTests(const UnitTest& unit_test);\n static void PrintFailedTestSuites(const UnitTest& unit_test);\n static void PrintSkippedTests(const UnitTest& unit_test);\n};\n\n // Fired before each iteration of tests starts.\nvoid PrettyUnitTestResultPrinter::OnTestIterationStart(\n const UnitTest& unit_test, int iteration) {\n if (GTEST_FLAG(repeat) != 1)\n printf(\"\\nRepeating all tests (iteration %d) . . .\\n\\n\", iteration + 1);\n\n const char* const filter = GTEST_FLAG(filter).c_str();\n\n // Prints the filter if it's not *. This reminds the user that some\n // tests may be skipped.\n if (!String::CStringEquals(filter, kUniversalFilter)) {\n ColoredPrintf(GTestColor::kYellow, \"Note: %s filter = %s\\n\", GTEST_NAME_,\n filter);\n }\n\n if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {\n const int32_t shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);\n ColoredPrintf(GTestColor::kYellow, \"Note: This is test shard %d of %s.\\n\",\n static_cast(shard_index) + 1,\n internal::posix::GetEnv(kTestTotalShards));\n }\n\n if (GTEST_FLAG(shuffle)) {\n ColoredPrintf(GTestColor::kYellow,\n \"Note: Randomizing tests' orders with a seed of %d .\\n\",\n unit_test.random_seed());\n }\n\n ColoredPrintf(GTestColor::kGreen, \"[==========] \");\n printf(\"Running %s from %s.\\n\",\n FormatTestCount(unit_test.test_to_run_count()).c_str(),\n FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());\n fflush(stdout);\n}\n\nvoid PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(\n const UnitTest& /*unit_test*/) {\n ColoredPrintf(GTestColor::kGreen, \"[----------] \");\n printf(\"Global test environment set-up.\\n\");\n fflush(stdout);\n}\n\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\nvoid PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {\n const std::string counts =\n FormatCountableNoun(test_case.test_to_run_count(), \"test\", \"tests\");\n ColoredPrintf(GTestColor::kGreen, \"[----------] \");\n printf(\"%s from %s\", counts.c_str(), test_case.name());\n if (test_case.type_param() == nullptr) {\n printf(\"\\n\");\n } else {\n printf(\", where %s = %s\\n\", kTypeParamLabel, test_case.type_param());\n }\n fflush(stdout);\n}\n#else\nvoid PrettyUnitTestResultPrinter::OnTestSuiteStart(\n const TestSuite& test_suite) {\n const std::string counts =\n FormatCountableNoun(test_suite.test_to_run_count(), \"test\", \"tests\");\n ColoredPrintf(GTestColor::kGreen, \"[----------] \");\n printf(\"%s from %s\", counts.c_str(), test_suite.name());\n if (test_suite.type_param() == nullptr) {\n printf(\"\\n\");\n } else {\n printf(\", where %s = %s\\n\", kTypeParamLabel, test_suite.type_param());\n }\n fflush(stdout);\n}\n#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\nvoid PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {\n ColoredPrintf(GTestColor::kGreen, \"[ RUN ] \");\n PrintTestName(test_info.test_suite_name(), test_info.name());\n printf(\"\\n\");\n fflush(stdout);\n}\n\n// Called after an assertion failure.\nvoid PrettyUnitTestResultPrinter::OnTestPartResult(\n const TestPartResult& result) {\n switch (result.type()) {\n // If the test part succeeded, we don't need to do anything.\n case TestPartResult::kSuccess:\n return;\n default:\n // Print failure message from the assertion\n // (e.g. expected this and got that).\n PrintTestPartResult(result);\n fflush(stdout);\n }\n}\n\nvoid PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {\n if (test_info.result()->Passed()) {\n ColoredPrintf(GTestColor::kGreen, \"[ OK ] \");\n } else if (test_info.result()->Skipped()) {\n ColoredPrintf(GTestColor::kGreen, \"[ SKIPPED ] \");\n } else {\n ColoredPrintf(GTestColor::kRed, \"[ FAILED ] \");\n }\n PrintTestName(test_info.test_suite_name(), test_info.name());\n if (test_info.result()->Failed())\n PrintFullTestCommentIfPresent(test_info);\n\n if (GTEST_FLAG(print_time)) {\n printf(\" (%s ms)\\n\", internal::StreamableToString(\n test_info.result()->elapsed_time()).c_str());\n } else {\n printf(\"\\n\");\n }\n fflush(stdout);\n}\n\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\nvoid PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {\n if (!GTEST_FLAG(print_time)) return;\n\n const std::string counts =\n FormatCountableNoun(test_case.test_to_run_count(), \"test\", \"tests\");\n ColoredPrintf(GTestColor::kGreen, \"[----------] \");\n printf(\"%s from %s (%s ms total)\\n\\n\", counts.c_str(), test_case.name(),\n internal::StreamableToString(test_case.elapsed_time()).c_str());\n fflush(stdout);\n}\n#else\nvoid PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite& test_suite) {\n if (!GTEST_FLAG(print_time)) return;\n\n const std::string counts =\n FormatCountableNoun(test_suite.test_to_run_count(), \"test\", \"tests\");\n ColoredPrintf(GTestColor::kGreen, \"[----------] \");\n printf(\"%s from %s (%s ms total)\\n\\n\", counts.c_str(), test_suite.name(),\n internal::StreamableToString(test_suite.elapsed_time()).c_str());\n fflush(stdout);\n}\n#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\nvoid PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(\n const UnitTest& /*unit_test*/) {\n ColoredPrintf(GTestColor::kGreen, \"[----------] \");\n printf(\"Global test environment tear-down\\n\");\n fflush(stdout);\n}\n\n// Internal helper for printing the list of failed tests.\nvoid PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {\n const int failed_test_count = unit_test.failed_test_count();\n ColoredPrintf(GTestColor::kRed, \"[ FAILED ] \");\n printf(\"%s, listed below:\\n\", FormatTestCount(failed_test_count).c_str());\n\n for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {\n const TestSuite& test_suite = *unit_test.GetTestSuite(i);\n if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) {\n continue;\n }\n for (int j = 0; j < test_suite.total_test_count(); ++j) {\n const TestInfo& test_info = *test_suite.GetTestInfo(j);\n if (!test_info.should_run() || !test_info.result()->Failed()) {\n continue;\n }\n ColoredPrintf(GTestColor::kRed, \"[ FAILED ] \");\n printf(\"%s.%s\", test_suite.name(), test_info.name());\n PrintFullTestCommentIfPresent(test_info);\n printf(\"\\n\");\n }\n }\n printf(\"\\n%2d FAILED %s\\n\", failed_test_count,\n failed_test_count == 1 ? \"TEST\" : \"TESTS\");\n}\n\n// Internal helper for printing the list of test suite failures not covered by\n// PrintFailedTests.\nvoid PrettyUnitTestResultPrinter::PrintFailedTestSuites(\n const UnitTest& unit_test) {\n int suite_failure_count = 0;\n for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {\n const TestSuite& test_suite = *unit_test.GetTestSuite(i);\n if (!test_suite.should_run()) {\n continue;\n }\n if (test_suite.ad_hoc_test_result().Failed()) {\n ColoredPrintf(GTestColor::kRed, \"[ FAILED ] \");\n printf(\"%s: SetUpTestSuite or TearDownTestSuite\\n\", test_suite.name());\n ++suite_failure_count;\n }\n }\n if (suite_failure_count > 0) {\n printf(\"\\n%2d FAILED TEST %s\\n\", suite_failure_count,\n suite_failure_count == 1 ? \"SUITE\" : \"SUITES\");\n }\n}\n\n// Internal helper for printing the list of skipped tests.\nvoid PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) {\n const int skipped_test_count = unit_test.skipped_test_count();\n if (skipped_test_count == 0) {\n return;\n }\n\n for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {\n const TestSuite& test_suite = *unit_test.GetTestSuite(i);\n if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) {\n continue;\n }\n for (int j = 0; j < test_suite.total_test_count(); ++j) {\n const TestInfo& test_info = *test_suite.GetTestInfo(j);\n if (!test_info.should_run() || !test_info.result()->Skipped()) {\n continue;\n }\n ColoredPrintf(GTestColor::kGreen, \"[ SKIPPED ] \");\n printf(\"%s.%s\", test_suite.name(), test_info.name());\n printf(\"\\n\");\n }\n }\n}\n\nvoid PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,\n int /*iteration*/) {\n ColoredPrintf(GTestColor::kGreen, \"[==========] \");\n printf(\"%s from %s ran.\",\n FormatTestCount(unit_test.test_to_run_count()).c_str(),\n FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());\n if (GTEST_FLAG(print_time)) {\n printf(\" (%s ms total)\",\n internal::StreamableToString(unit_test.elapsed_time()).c_str());\n }\n printf(\"\\n\");\n ColoredPrintf(GTestColor::kGreen, \"[ PASSED ] \");\n printf(\"%s.\\n\", FormatTestCount(unit_test.successful_test_count()).c_str());\n\n const int skipped_test_count = unit_test.skipped_test_count();\n if (skipped_test_count > 0) {\n ColoredPrintf(GTestColor::kGreen, \"[ SKIPPED ] \");\n printf(\"%s, listed below:\\n\", FormatTestCount(skipped_test_count).c_str());\n PrintSkippedTests(unit_test);\n }\n\n if (!unit_test.Passed()) {\n PrintFailedTests(unit_test);\n PrintFailedTestSuites(unit_test);\n }\n\n int num_disabled = unit_test.reportable_disabled_test_count();\n if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {\n if (unit_test.Passed()) {\n printf(\"\\n\"); // Add a spacer if no FAILURE banner is displayed.\n }\n ColoredPrintf(GTestColor::kYellow, \" YOU HAVE %d DISABLED %s\\n\\n\",\n num_disabled, num_disabled == 1 ? \"TEST\" : \"TESTS\");\n }\n // Ensure that Google Test output is printed before, e.g., heapchecker output.\n fflush(stdout);\n}\n\n// End PrettyUnitTestResultPrinter\n\n// This class implements the TestEventListener interface.\n//\n// Class BriefUnitTestResultPrinter is copyable.\nclass BriefUnitTestResultPrinter : public TestEventListener {\n public:\n BriefUnitTestResultPrinter() {}\n static void PrintTestName(const char* test_suite, const char* test) {\n printf(\"%s.%s\", test_suite, test);\n }\n\n // The following methods override what's in the TestEventListener class.\n void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}\n void OnTestIterationStart(const UnitTest& /*unit_test*/,\n int /*iteration*/) override {}\n void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}\n void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n void OnTestCaseStart(const TestCase& /*test_case*/) override {}\n#else\n void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}\n#endif // OnTestCaseStart\n\n void OnTestStart(const TestInfo& /*test_info*/) override {}\n\n void OnTestPartResult(const TestPartResult& result) override;\n void OnTestEnd(const TestInfo& test_info) override;\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n void OnTestCaseEnd(const TestCase& /*test_case*/) override {}\n#else\n void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}\n#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}\n void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}\n void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;\n void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}\n};\n\n// Called after an assertion failure.\nvoid BriefUnitTestResultPrinter::OnTestPartResult(\n const TestPartResult& result) {\n switch (result.type()) {\n // If the test part succeeded, we don't need to do anything.\n case TestPartResult::kSuccess:\n return;\n default:\n // Print failure message from the assertion\n // (e.g. expected this and got that).\n PrintTestPartResult(result);\n fflush(stdout);\n }\n}\n\nvoid BriefUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {\n if (test_info.result()->Failed()) {\n ColoredPrintf(GTestColor::kRed, \"[ FAILED ] \");\n PrintTestName(test_info.test_suite_name(), test_info.name());\n PrintFullTestCommentIfPresent(test_info);\n\n if (GTEST_FLAG(print_time)) {\n printf(\" (%s ms)\\n\",\n internal::StreamableToString(test_info.result()->elapsed_time())\n .c_str());\n } else {\n printf(\"\\n\");\n }\n fflush(stdout);\n }\n}\n\nvoid BriefUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,\n int /*iteration*/) {\n ColoredPrintf(GTestColor::kGreen, \"[==========] \");\n printf(\"%s from %s ran.\",\n FormatTestCount(unit_test.test_to_run_count()).c_str(),\n FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());\n if (GTEST_FLAG(print_time)) {\n printf(\" (%s ms total)\",\n internal::StreamableToString(unit_test.elapsed_time()).c_str());\n }\n printf(\"\\n\");\n ColoredPrintf(GTestColor::kGreen, \"[ PASSED ] \");\n printf(\"%s.\\n\", FormatTestCount(unit_test.successful_test_count()).c_str());\n\n const int skipped_test_count = unit_test.skipped_test_count();\n if (skipped_test_count > 0) {\n ColoredPrintf(GTestColor::kGreen, \"[ SKIPPED ] \");\n printf(\"%s.\\n\", FormatTestCount(skipped_test_count).c_str());\n }\n\n int num_disabled = unit_test.reportable_disabled_test_count();\n if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {\n if (unit_test.Passed()) {\n printf(\"\\n\"); // Add a spacer if no FAILURE banner is displayed.\n }\n ColoredPrintf(GTestColor::kYellow, \" YOU HAVE %d DISABLED %s\\n\\n\",\n num_disabled, num_disabled == 1 ? \"TEST\" : \"TESTS\");\n }\n // Ensure that Google Test output is printed before, e.g., heapchecker output.\n fflush(stdout);\n}\n\n// End BriefUnitTestResultPrinter\n\n// class TestEventRepeater\n//\n// This class forwards events to other event listeners.\nclass TestEventRepeater : public TestEventListener {\n public:\n TestEventRepeater() : forwarding_enabled_(true) {}\n ~TestEventRepeater() override;\n void Append(TestEventListener *listener);\n TestEventListener* Release(TestEventListener* listener);\n\n // Controls whether events will be forwarded to listeners_. Set to false\n // in death test child processes.\n bool forwarding_enabled() const { return forwarding_enabled_; }\n void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }\n\n void OnTestProgramStart(const UnitTest& unit_test) override;\n void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;\n void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;\n void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) override;\n// Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n void OnTestCaseStart(const TestSuite& parameter) override;\n#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n void OnTestSuiteStart(const TestSuite& parameter) override;\n void OnTestStart(const TestInfo& test_info) override;\n void OnTestPartResult(const TestPartResult& result) override;\n void OnTestEnd(const TestInfo& test_info) override;\n// Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n void OnTestCaseEnd(const TestCase& parameter) override;\n#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n void OnTestSuiteEnd(const TestSuite& parameter) override;\n void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;\n void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) override;\n void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;\n void OnTestProgramEnd(const UnitTest& unit_test) override;\n\n private:\n // Controls whether events will be forwarded to listeners_. Set to false\n // in death test child processes.\n bool forwarding_enabled_;\n // The list of listeners that receive events.\n std::vector listeners_;\n\n GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);\n};\n\nTestEventRepeater::~TestEventRepeater() {\n ForEach(listeners_, Delete);\n}\n\nvoid TestEventRepeater::Append(TestEventListener *listener) {\n listeners_.push_back(listener);\n}\n\nTestEventListener* TestEventRepeater::Release(TestEventListener *listener) {\n for (size_t i = 0; i < listeners_.size(); ++i) {\n if (listeners_[i] == listener) {\n listeners_.erase(listeners_.begin() + static_cast(i));\n return listener;\n }\n }\n\n return nullptr;\n}\n\n// Since most methods are very similar, use macros to reduce boilerplate.\n// This defines a member that forwards the call to all listeners.\n#define GTEST_REPEATER_METHOD_(Name, Type) \\\nvoid TestEventRepeater::Name(const Type& parameter) { \\\n if (forwarding_enabled_) { \\\n for (size_t i = 0; i < listeners_.size(); i++) { \\\n listeners_[i]->Name(parameter); \\\n } \\\n } \\\n}\n// This defines a member that forwards the call to all listeners in reverse\n// order.\n#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \\\n void TestEventRepeater::Name(const Type& parameter) { \\\n if (forwarding_enabled_) { \\\n for (size_t i = listeners_.size(); i != 0; i--) { \\\n listeners_[i - 1]->Name(parameter); \\\n } \\\n } \\\n }\n\nGTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)\nGTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)\n// Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\nGTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite)\n#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\nGTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite)\nGTEST_REPEATER_METHOD_(OnTestStart, TestInfo)\nGTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)\nGTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)\nGTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)\nGTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)\nGTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)\n// Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\nGTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestSuite)\n#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\nGTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd, TestSuite)\nGTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)\n\n#undef GTEST_REPEATER_METHOD_\n#undef GTEST_REVERSE_REPEATER_METHOD_\n\nvoid TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,\n int iteration) {\n if (forwarding_enabled_) {\n for (size_t i = 0; i < listeners_.size(); i++) {\n listeners_[i]->OnTestIterationStart(unit_test, iteration);\n }\n }\n}\n\nvoid TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,\n int iteration) {\n if (forwarding_enabled_) {\n for (size_t i = listeners_.size(); i > 0; i--) {\n listeners_[i - 1]->OnTestIterationEnd(unit_test, iteration);\n }\n }\n}\n\n// End TestEventRepeater\n\n// This class generates an XML output file.\nclass XmlUnitTestResultPrinter : public EmptyTestEventListener {\n public:\n explicit XmlUnitTestResultPrinter(const char* output_file);\n\n void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;\n void ListTestsMatchingFilter(const std::vector& test_suites);\n\n // Prints an XML summary of all unit tests.\n static void PrintXmlTestsList(std::ostream* stream,\n const std::vector& test_suites);\n\n private:\n // Is c a whitespace character that is normalized to a space character\n // when it appears in an XML attribute value?\n static bool IsNormalizableWhitespace(char c) {\n return c == 0x9 || c == 0xA || c == 0xD;\n }\n\n // May c appear in a well-formed XML document?\n static bool IsValidXmlCharacter(char c) {\n return IsNormalizableWhitespace(c) || c >= 0x20;\n }\n\n // Returns an XML-escaped copy of the input string str. If\n // is_attribute is true, the text is meant to appear as an attribute\n // value, and normalizable whitespace is preserved by replacing it\n // with character references.\n static std::string EscapeXml(const std::string& str, bool is_attribute);\n\n // Returns the given string with all characters invalid in XML removed.\n static std::string RemoveInvalidXmlCharacters(const std::string& str);\n\n // Convenience wrapper around EscapeXml when str is an attribute value.\n static std::string EscapeXmlAttribute(const std::string& str) {\n return EscapeXml(str, true);\n }\n\n // Convenience wrapper around EscapeXml when str is not an attribute value.\n static std::string EscapeXmlText(const char* str) {\n return EscapeXml(str, false);\n }\n\n // Verifies that the given attribute belongs to the given element and\n // streams the attribute as XML.\n static void OutputXmlAttribute(std::ostream* stream,\n const std::string& element_name,\n const std::string& name,\n const std::string& value);\n\n // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.\n static void OutputXmlCDataSection(::std::ostream* stream, const char* data);\n\n // Streams a test suite XML stanza containing the given test result.\n //\n // Requires: result.Failed()\n static void OutputXmlTestSuiteForTestResult(::std::ostream* stream,\n const TestResult& result);\n\n // Streams an XML representation of a TestResult object.\n static void OutputXmlTestResult(::std::ostream* stream,\n const TestResult& result);\n\n // Streams an XML representation of a TestInfo object.\n static void OutputXmlTestInfo(::std::ostream* stream,\n const char* test_suite_name,\n const TestInfo& test_info);\n\n // Prints an XML representation of a TestSuite object\n static void PrintXmlTestSuite(::std::ostream* stream,\n const TestSuite& test_suite);\n\n // Prints an XML summary of unit_test to output stream out.\n static void PrintXmlUnitTest(::std::ostream* stream,\n const UnitTest& unit_test);\n\n // Produces a string representing the test properties in a result as space\n // delimited XML attributes based on the property key=\"value\" pairs.\n // When the std::string is not empty, it includes a space at the beginning,\n // to delimit this attribute from prior attributes.\n static std::string TestPropertiesAsXmlAttributes(const TestResult& result);\n\n // Streams an XML representation of the test properties of a TestResult\n // object.\n static void OutputXmlTestProperties(std::ostream* stream,\n const TestResult& result);\n\n // The output file.\n const std::string output_file_;\n\n GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);\n};\n\n// Creates a new XmlUnitTestResultPrinter.\nXmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)\n : output_file_(output_file) {\n if (output_file_.empty()) {\n GTEST_LOG_(FATAL) << \"XML output file may not be null\";\n }\n}\n\n// Called after the unit test ends.\nvoid XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,\n int /*iteration*/) {\n FILE* xmlout = OpenFileForWriting(output_file_);\n std::stringstream stream;\n PrintXmlUnitTest(&stream, unit_test);\n fprintf(xmlout, \"%s\", StringStreamToString(&stream).c_str());\n fclose(xmlout);\n}\n\nvoid XmlUnitTestResultPrinter::ListTestsMatchingFilter(\n const std::vector& test_suites) {\n FILE* xmlout = OpenFileForWriting(output_file_);\n std::stringstream stream;\n PrintXmlTestsList(&stream, test_suites);\n fprintf(xmlout, \"%s\", StringStreamToString(&stream).c_str());\n fclose(xmlout);\n}\n\n// Returns an XML-escaped copy of the input string str. If is_attribute\n// is true, the text is meant to appear as an attribute value, and\n// normalizable whitespace is preserved by replacing it with character\n// references.\n//\n// Invalid XML characters in str, if any, are stripped from the output.\n// It is expected that most, if not all, of the text processed by this\n// module will consist of ordinary English text.\n// If this module is ever modified to produce version 1.1 XML output,\n// most invalid characters can be retained using character references.\nstd::string XmlUnitTestResultPrinter::EscapeXml(\n const std::string& str, bool is_attribute) {\n Message m;\n\n for (size_t i = 0; i < str.size(); ++i) {\n const char ch = str[i];\n switch (ch) {\n case '<':\n m << \"<\";\n break;\n case '>':\n m << \">\";\n break;\n case '&':\n m << \"&\";\n break;\n case '\\'':\n if (is_attribute)\n m << \"'\";\n else\n m << '\\'';\n break;\n case '\"':\n if (is_attribute)\n m << \""\";\n else\n m << '\"';\n break;\n default:\n if (IsValidXmlCharacter(ch)) {\n if (is_attribute && IsNormalizableWhitespace(ch))\n m << \"&#x\" << String::FormatByte(static_cast(ch))\n << \";\";\n else\n m << ch;\n }\n break;\n }\n }\n\n return m.GetString();\n}\n\n// Returns the given string with all characters invalid in XML removed.\n// Currently invalid characters are dropped from the string. An\n// alternative is to replace them with certain characters such as . or ?.\nstd::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(\n const std::string& str) {\n std::string output;\n output.reserve(str.size());\n for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)\n if (IsValidXmlCharacter(*it))\n output.push_back(*it);\n\n return output;\n}\n\n// The following routines generate an XML representation of a UnitTest\n// object.\n// GOOGLETEST_CM0009 DO NOT DELETE\n//\n// This is how Google Test concepts map to the DTD:\n//\n// <-- corresponds to a UnitTest object\n// <-- corresponds to a TestSuite object\n// <-- corresponds to a TestInfo object\n// ...\n// ...\n// ...\n// <-- individual assertion failures\n// \n// \n// \n\n// Formats the given time in milliseconds as seconds.\nstd::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {\n ::std::stringstream ss;\n ss << (static_cast(ms) * 1e-3);\n return ss.str();\n}\n\nstatic bool PortableLocaltime(time_t seconds, struct tm* out) {\n#if defined(_MSC_VER)\n return localtime_s(out, &seconds) == 0;\n#elif defined(__MINGW32__) || defined(__MINGW64__)\n // MINGW provides neither localtime_r nor localtime_s, but uses\n // Windows' localtime(), which has a thread-local tm buffer.\n struct tm* tm_ptr = localtime(&seconds); // NOLINT\n if (tm_ptr == nullptr) return false;\n *out = *tm_ptr;\n return true;\n#elif defined(__STDC_LIB_EXT1__)\n // Uses localtime_s when available as localtime_r is only available from\n // C23 standard.\n return localtime_s(&seconds, out) != nullptr;\n#else\n return localtime_r(&seconds, out) != nullptr;\n#endif\n}\n\n// Converts the given epoch time in milliseconds to a date string in the ISO\n// 8601 format, without the timezone information.\nstd::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {\n struct tm time_struct;\n if (!PortableLocaltime(static_cast(ms / 1000), &time_struct))\n return \"\";\n // YYYY-MM-DDThh:mm:ss.sss\n return StreamableToString(time_struct.tm_year + 1900) + \"-\" +\n String::FormatIntWidth2(time_struct.tm_mon + 1) + \"-\" +\n String::FormatIntWidth2(time_struct.tm_mday) + \"T\" +\n String::FormatIntWidth2(time_struct.tm_hour) + \":\" +\n String::FormatIntWidth2(time_struct.tm_min) + \":\" +\n String::FormatIntWidth2(time_struct.tm_sec) + \".\" +\n String::FormatIntWidthN(static_cast(ms % 1000), 3);\n}\n\n// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.\nvoid XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,\n const char* data) {\n const char* segment = data;\n *stream << \"\");\n if (next_segment != nullptr) {\n stream->write(\n segment, static_cast(next_segment - segment));\n *stream << \"]]>]]>\");\n } else {\n *stream << segment;\n break;\n }\n }\n *stream << \"]]>\";\n}\n\nvoid XmlUnitTestResultPrinter::OutputXmlAttribute(\n std::ostream* stream,\n const std::string& element_name,\n const std::string& name,\n const std::string& value) {\n const std::vector& allowed_names =\n GetReservedOutputAttributesForElement(element_name);\n\n GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=\n allowed_names.end())\n << \"Attribute \" << name << \" is not allowed for element <\" << element_name\n << \">.\";\n\n *stream << \" \" << name << \"=\\\"\" << EscapeXmlAttribute(value) << \"\\\"\";\n}\n\n// Streams a test suite XML stanza containing the given test result.\nvoid XmlUnitTestResultPrinter::OutputXmlTestSuiteForTestResult(\n ::std::ostream* stream, const TestResult& result) {\n // Output the boilerplate for a minimal test suite with one test.\n *stream << \" \";\n\n // Output the boilerplate for a minimal test case with a single test.\n *stream << \" \\n\";\n}\n\n// Prints an XML representation of a TestInfo object.\nvoid XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,\n const char* test_suite_name,\n const TestInfo& test_info) {\n const TestResult& result = *test_info.result();\n const std::string kTestsuite = \"testcase\";\n\n if (test_info.is_in_another_shard()) {\n return;\n }\n\n *stream << \" \\n\";\n return;\n }\n\n OutputXmlAttribute(stream, kTestsuite, \"status\",\n test_info.should_run() ? \"run\" : \"notrun\");\n OutputXmlAttribute(stream, kTestsuite, \"result\",\n test_info.should_run()\n ? (result.Skipped() ? \"skipped\" : \"completed\")\n : \"suppressed\");\n OutputXmlAttribute(stream, kTestsuite, \"time\",\n FormatTimeInMillisAsSeconds(result.elapsed_time()));\n OutputXmlAttribute(\n stream, kTestsuite, \"timestamp\",\n FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));\n OutputXmlAttribute(stream, kTestsuite, \"classname\", test_suite_name);\n\n OutputXmlTestResult(stream, result);\n}\n\nvoid XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream,\n const TestResult& result) {\n int failures = 0;\n int skips = 0;\n for (int i = 0; i < result.total_part_count(); ++i) {\n const TestPartResult& part = result.GetTestPartResult(i);\n if (part.failed()) {\n if (++failures == 1 && skips == 0) {\n *stream << \">\\n\";\n }\n const std::string location =\n internal::FormatCompilerIndependentFileLocation(part.file_name(),\n part.line_number());\n const std::string summary = location + \"\\n\" + part.summary();\n *stream << \" \";\n const std::string detail = location + \"\\n\" + part.message();\n OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());\n *stream << \"\\n\";\n } else if (part.skipped()) {\n if (++skips == 1 && failures == 0) {\n *stream << \">\\n\";\n }\n const std::string location =\n internal::FormatCompilerIndependentFileLocation(part.file_name(),\n part.line_number());\n const std::string summary = location + \"\\n\" + part.summary();\n *stream << \" \";\n const std::string detail = location + \"\\n\" + part.message();\n OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());\n *stream << \"\\n\";\n }\n }\n\n if (failures == 0 && skips == 0 && result.test_property_count() == 0) {\n *stream << \" />\\n\";\n } else {\n if (failures == 0 && skips == 0) {\n *stream << \">\\n\";\n }\n OutputXmlTestProperties(stream, result);\n *stream << \" \\n\";\n }\n}\n\n// Prints an XML representation of a TestSuite object\nvoid XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,\n const TestSuite& test_suite) {\n const std::string kTestsuite = \"testsuite\";\n *stream << \" <\" << kTestsuite;\n OutputXmlAttribute(stream, kTestsuite, \"name\", test_suite.name());\n OutputXmlAttribute(stream, kTestsuite, \"tests\",\n StreamableToString(test_suite.reportable_test_count()));\n if (!GTEST_FLAG(list_tests)) {\n OutputXmlAttribute(stream, kTestsuite, \"failures\",\n StreamableToString(test_suite.failed_test_count()));\n OutputXmlAttribute(\n stream, kTestsuite, \"disabled\",\n StreamableToString(test_suite.reportable_disabled_test_count()));\n OutputXmlAttribute(stream, kTestsuite, \"skipped\",\n StreamableToString(test_suite.skipped_test_count()));\n\n OutputXmlAttribute(stream, kTestsuite, \"errors\", \"0\");\n\n OutputXmlAttribute(stream, kTestsuite, \"time\",\n FormatTimeInMillisAsSeconds(test_suite.elapsed_time()));\n OutputXmlAttribute(\n stream, kTestsuite, \"timestamp\",\n FormatEpochTimeInMillisAsIso8601(test_suite.start_timestamp()));\n *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result());\n }\n *stream << \">\\n\";\n for (int i = 0; i < test_suite.total_test_count(); ++i) {\n if (test_suite.GetTestInfo(i)->is_reportable())\n OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));\n }\n *stream << \" \\n\";\n}\n\n// Prints an XML summary of unit_test to output stream out.\nvoid XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,\n const UnitTest& unit_test) {\n const std::string kTestsuites = \"testsuites\";\n\n *stream << \"\\n\";\n *stream << \"<\" << kTestsuites;\n\n OutputXmlAttribute(stream, kTestsuites, \"tests\",\n StreamableToString(unit_test.reportable_test_count()));\n OutputXmlAttribute(stream, kTestsuites, \"failures\",\n StreamableToString(unit_test.failed_test_count()));\n OutputXmlAttribute(\n stream, kTestsuites, \"disabled\",\n StreamableToString(unit_test.reportable_disabled_test_count()));\n OutputXmlAttribute(stream, kTestsuites, \"errors\", \"0\");\n OutputXmlAttribute(stream, kTestsuites, \"time\",\n FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));\n OutputXmlAttribute(\n stream, kTestsuites, \"timestamp\",\n FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));\n\n if (GTEST_FLAG(shuffle)) {\n OutputXmlAttribute(stream, kTestsuites, \"random_seed\",\n StreamableToString(unit_test.random_seed()));\n }\n *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());\n\n OutputXmlAttribute(stream, kTestsuites, \"name\", \"AllTests\");\n *stream << \">\\n\";\n\n for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {\n if (unit_test.GetTestSuite(i)->reportable_test_count() > 0)\n PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i));\n }\n\n // If there was a test failure outside of one of the test suites (like in a\n // test environment) include that in the output.\n if (unit_test.ad_hoc_test_result().Failed()) {\n OutputXmlTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());\n }\n\n *stream << \"\\n\";\n}\n\nvoid XmlUnitTestResultPrinter::PrintXmlTestsList(\n std::ostream* stream, const std::vector& test_suites) {\n const std::string kTestsuites = \"testsuites\";\n\n *stream << \"\\n\";\n *stream << \"<\" << kTestsuites;\n\n int total_tests = 0;\n for (auto test_suite : test_suites) {\n total_tests += test_suite->total_test_count();\n }\n OutputXmlAttribute(stream, kTestsuites, \"tests\",\n StreamableToString(total_tests));\n OutputXmlAttribute(stream, kTestsuites, \"name\", \"AllTests\");\n *stream << \">\\n\";\n\n for (auto test_suite : test_suites) {\n PrintXmlTestSuite(stream, *test_suite);\n }\n *stream << \"\\n\";\n}\n\n// Produces a string representing the test properties in a result as space\n// delimited XML attributes based on the property key=\"value\" pairs.\nstd::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(\n const TestResult& result) {\n Message attributes;\n for (int i = 0; i < result.test_property_count(); ++i) {\n const TestProperty& property = result.GetTestProperty(i);\n attributes << \" \" << property.key() << \"=\"\n << \"\\\"\" << EscapeXmlAttribute(property.value()) << \"\\\"\";\n }\n return attributes.GetString();\n}\n\nvoid XmlUnitTestResultPrinter::OutputXmlTestProperties(\n std::ostream* stream, const TestResult& result) {\n const std::string kProperties = \"properties\";\n const std::string kProperty = \"property\";\n\n if (result.test_property_count() <= 0) {\n return;\n }\n\n *stream << \"<\" << kProperties << \">\\n\";\n for (int i = 0; i < result.test_property_count(); ++i) {\n const TestProperty& property = result.GetTestProperty(i);\n *stream << \"<\" << kProperty;\n *stream << \" name=\\\"\" << EscapeXmlAttribute(property.key()) << \"\\\"\";\n *stream << \" value=\\\"\" << EscapeXmlAttribute(property.value()) << \"\\\"\";\n *stream << \"/>\\n\";\n }\n *stream << \"\\n\";\n}\n\n// End XmlUnitTestResultPrinter\n\n// This class generates an JSON output file.\nclass JsonUnitTestResultPrinter : public EmptyTestEventListener {\n public:\n explicit JsonUnitTestResultPrinter(const char* output_file);\n\n void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;\n\n // Prints an JSON summary of all unit tests.\n static void PrintJsonTestList(::std::ostream* stream,\n const std::vector& test_suites);\n\n private:\n // Returns an JSON-escaped copy of the input string str.\n static std::string EscapeJson(const std::string& str);\n\n //// Verifies that the given attribute belongs to the given element and\n //// streams the attribute as JSON.\n static void OutputJsonKey(std::ostream* stream,\n const std::string& element_name,\n const std::string& name,\n const std::string& value,\n const std::string& indent,\n bool comma = true);\n static void OutputJsonKey(std::ostream* stream,\n const std::string& element_name,\n const std::string& name,\n int value,\n const std::string& indent,\n bool comma = true);\n\n // Streams a test suite JSON stanza containing the given test result.\n //\n // Requires: result.Failed()\n static void OutputJsonTestSuiteForTestResult(::std::ostream* stream,\n const TestResult& result);\n\n // Streams a JSON representation of a TestResult object.\n static void OutputJsonTestResult(::std::ostream* stream,\n const TestResult& result);\n\n // Streams a JSON representation of a TestInfo object.\n static void OutputJsonTestInfo(::std::ostream* stream,\n const char* test_suite_name,\n const TestInfo& test_info);\n\n // Prints a JSON representation of a TestSuite object\n static void PrintJsonTestSuite(::std::ostream* stream,\n const TestSuite& test_suite);\n\n // Prints a JSON summary of unit_test to output stream out.\n static void PrintJsonUnitTest(::std::ostream* stream,\n const UnitTest& unit_test);\n\n // Produces a string representing the test properties in a result as\n // a JSON dictionary.\n static std::string TestPropertiesAsJson(const TestResult& result,\n const std::string& indent);\n\n // The output file.\n const std::string output_file_;\n\n GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter);\n};\n\n// Creates a new JsonUnitTestResultPrinter.\nJsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)\n : output_file_(output_file) {\n if (output_file_.empty()) {\n GTEST_LOG_(FATAL) << \"JSON output file may not be null\";\n }\n}\n\nvoid JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,\n int /*iteration*/) {\n FILE* jsonout = OpenFileForWriting(output_file_);\n std::stringstream stream;\n PrintJsonUnitTest(&stream, unit_test);\n fprintf(jsonout, \"%s\", StringStreamToString(&stream).c_str());\n fclose(jsonout);\n}\n\n// Returns an JSON-escaped copy of the input string str.\nstd::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {\n Message m;\n\n for (size_t i = 0; i < str.size(); ++i) {\n const char ch = str[i];\n switch (ch) {\n case '\\\\':\n case '\"':\n case '/':\n m << '\\\\' << ch;\n break;\n case '\\b':\n m << \"\\\\b\";\n break;\n case '\\t':\n m << \"\\\\t\";\n break;\n case '\\n':\n m << \"\\\\n\";\n break;\n case '\\f':\n m << \"\\\\f\";\n break;\n case '\\r':\n m << \"\\\\r\";\n break;\n default:\n if (ch < ' ') {\n m << \"\\\\u00\" << String::FormatByte(static_cast(ch));\n } else {\n m << ch;\n }\n break;\n }\n }\n\n return m.GetString();\n}\n\n// The following routines generate an JSON representation of a UnitTest\n// object.\n\n// Formats the given time in milliseconds as seconds.\nstatic std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {\n ::std::stringstream ss;\n ss << (static_cast(ms) * 1e-3) << \"s\";\n return ss.str();\n}\n\n// Converts the given epoch time in milliseconds to a date string in the\n// RFC3339 format, without the timezone information.\nstatic std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {\n struct tm time_struct;\n if (!PortableLocaltime(static_cast(ms / 1000), &time_struct))\n return \"\";\n // YYYY-MM-DDThh:mm:ss\n return StreamableToString(time_struct.tm_year + 1900) + \"-\" +\n String::FormatIntWidth2(time_struct.tm_mon + 1) + \"-\" +\n String::FormatIntWidth2(time_struct.tm_mday) + \"T\" +\n String::FormatIntWidth2(time_struct.tm_hour) + \":\" +\n String::FormatIntWidth2(time_struct.tm_min) + \":\" +\n String::FormatIntWidth2(time_struct.tm_sec) + \"Z\";\n}\n\nstatic inline std::string Indent(size_t width) {\n return std::string(width, ' ');\n}\n\nvoid JsonUnitTestResultPrinter::OutputJsonKey(\n std::ostream* stream,\n const std::string& element_name,\n const std::string& name,\n const std::string& value,\n const std::string& indent,\n bool comma) {\n const std::vector& allowed_names =\n GetReservedOutputAttributesForElement(element_name);\n\n GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=\n allowed_names.end())\n << \"Key \\\"\" << name << \"\\\" is not allowed for value \\\"\" << element_name\n << \"\\\".\";\n\n *stream << indent << \"\\\"\" << name << \"\\\": \\\"\" << EscapeJson(value) << \"\\\"\";\n if (comma)\n *stream << \",\\n\";\n}\n\nvoid JsonUnitTestResultPrinter::OutputJsonKey(\n std::ostream* stream,\n const std::string& element_name,\n const std::string& name,\n int value,\n const std::string& indent,\n bool comma) {\n const std::vector& allowed_names =\n GetReservedOutputAttributesForElement(element_name);\n\n GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=\n allowed_names.end())\n << \"Key \\\"\" << name << \"\\\" is not allowed for value \\\"\" << element_name\n << \"\\\".\";\n\n *stream << indent << \"\\\"\" << name << \"\\\": \" << StreamableToString(value);\n if (comma)\n *stream << \",\\n\";\n}\n\n// Streams a test suite JSON stanza containing the given test result.\nvoid JsonUnitTestResultPrinter::OutputJsonTestSuiteForTestResult(\n ::std::ostream* stream, const TestResult& result) {\n // Output the boilerplate for a new test suite.\n *stream << Indent(4) << \"{\\n\";\n OutputJsonKey(stream, \"testsuite\", \"name\", \"NonTestSuiteFailure\", Indent(6));\n OutputJsonKey(stream, \"testsuite\", \"tests\", 1, Indent(6));\n if (!GTEST_FLAG(list_tests)) {\n OutputJsonKey(stream, \"testsuite\", \"failures\", 1, Indent(6));\n OutputJsonKey(stream, \"testsuite\", \"disabled\", 0, Indent(6));\n OutputJsonKey(stream, \"testsuite\", \"skipped\", 0, Indent(6));\n OutputJsonKey(stream, \"testsuite\", \"errors\", 0, Indent(6));\n OutputJsonKey(stream, \"testsuite\", \"time\",\n FormatTimeInMillisAsDuration(result.elapsed_time()),\n Indent(6));\n OutputJsonKey(stream, \"testsuite\", \"timestamp\",\n FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),\n Indent(6));\n }\n *stream << Indent(6) << \"\\\"testsuite\\\": [\\n\";\n\n // Output the boilerplate for a new test case.\n *stream << Indent(8) << \"{\\n\";\n OutputJsonKey(stream, \"testcase\", \"name\", \"\", Indent(10));\n OutputJsonKey(stream, \"testcase\", \"status\", \"RUN\", Indent(10));\n OutputJsonKey(stream, \"testcase\", \"result\", \"COMPLETED\", Indent(10));\n OutputJsonKey(stream, \"testcase\", \"timestamp\",\n FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),\n Indent(10));\n OutputJsonKey(stream, \"testcase\", \"time\",\n FormatTimeInMillisAsDuration(result.elapsed_time()),\n Indent(10));\n OutputJsonKey(stream, \"testcase\", \"classname\", \"\", Indent(10), false);\n *stream << TestPropertiesAsJson(result, Indent(10));\n\n // Output the actual test result.\n OutputJsonTestResult(stream, result);\n\n // Finish the test suite.\n *stream << \"\\n\" << Indent(6) << \"]\\n\" << Indent(4) << \"}\";\n}\n\n// Prints a JSON representation of a TestInfo object.\nvoid JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,\n const char* test_suite_name,\n const TestInfo& test_info) {\n const TestResult& result = *test_info.result();\n const std::string kTestsuite = \"testcase\";\n const std::string kIndent = Indent(10);\n\n *stream << Indent(8) << \"{\\n\";\n OutputJsonKey(stream, kTestsuite, \"name\", test_info.name(), kIndent);\n\n if (test_info.value_param() != nullptr) {\n OutputJsonKey(stream, kTestsuite, \"value_param\", test_info.value_param(),\n kIndent);\n }\n if (test_info.type_param() != nullptr) {\n OutputJsonKey(stream, kTestsuite, \"type_param\", test_info.type_param(),\n kIndent);\n }\n if (GTEST_FLAG(list_tests)) {\n OutputJsonKey(stream, kTestsuite, \"file\", test_info.file(), kIndent);\n OutputJsonKey(stream, kTestsuite, \"line\", test_info.line(), kIndent, false);\n *stream << \"\\n\" << Indent(8) << \"}\";\n return;\n }\n\n OutputJsonKey(stream, kTestsuite, \"status\",\n test_info.should_run() ? \"RUN\" : \"NOTRUN\", kIndent);\n OutputJsonKey(stream, kTestsuite, \"result\",\n test_info.should_run()\n ? (result.Skipped() ? \"SKIPPED\" : \"COMPLETED\")\n : \"SUPPRESSED\",\n kIndent);\n OutputJsonKey(stream, kTestsuite, \"timestamp\",\n FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),\n kIndent);\n OutputJsonKey(stream, kTestsuite, \"time\",\n FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);\n OutputJsonKey(stream, kTestsuite, \"classname\", test_suite_name, kIndent,\n false);\n *stream << TestPropertiesAsJson(result, kIndent);\n\n OutputJsonTestResult(stream, result);\n}\n\nvoid JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream,\n const TestResult& result) {\n const std::string kIndent = Indent(10);\n\n int failures = 0;\n for (int i = 0; i < result.total_part_count(); ++i) {\n const TestPartResult& part = result.GetTestPartResult(i);\n if (part.failed()) {\n *stream << \",\\n\";\n if (++failures == 1) {\n *stream << kIndent << \"\\\"\" << \"failures\" << \"\\\": [\\n\";\n }\n const std::string location =\n internal::FormatCompilerIndependentFileLocation(part.file_name(),\n part.line_number());\n const std::string message = EscapeJson(location + \"\\n\" + part.message());\n *stream << kIndent << \" {\\n\"\n << kIndent << \" \\\"failure\\\": \\\"\" << message << \"\\\",\\n\"\n << kIndent << \" \\\"type\\\": \\\"\\\"\\n\"\n << kIndent << \" }\";\n }\n }\n\n if (failures > 0)\n *stream << \"\\n\" << kIndent << \"]\";\n *stream << \"\\n\" << Indent(8) << \"}\";\n}\n\n// Prints an JSON representation of a TestSuite object\nvoid JsonUnitTestResultPrinter::PrintJsonTestSuite(\n std::ostream* stream, const TestSuite& test_suite) {\n const std::string kTestsuite = \"testsuite\";\n const std::string kIndent = Indent(6);\n\n *stream << Indent(4) << \"{\\n\";\n OutputJsonKey(stream, kTestsuite, \"name\", test_suite.name(), kIndent);\n OutputJsonKey(stream, kTestsuite, \"tests\", test_suite.reportable_test_count(),\n kIndent);\n if (!GTEST_FLAG(list_tests)) {\n OutputJsonKey(stream, kTestsuite, \"failures\",\n test_suite.failed_test_count(), kIndent);\n OutputJsonKey(stream, kTestsuite, \"disabled\",\n test_suite.reportable_disabled_test_count(), kIndent);\n OutputJsonKey(stream, kTestsuite, \"errors\", 0, kIndent);\n OutputJsonKey(\n stream, kTestsuite, \"timestamp\",\n FormatEpochTimeInMillisAsRFC3339(test_suite.start_timestamp()),\n kIndent);\n OutputJsonKey(stream, kTestsuite, \"time\",\n FormatTimeInMillisAsDuration(test_suite.elapsed_time()),\n kIndent, false);\n *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent)\n << \",\\n\";\n }\n\n *stream << kIndent << \"\\\"\" << kTestsuite << \"\\\": [\\n\";\n\n bool comma = false;\n for (int i = 0; i < test_suite.total_test_count(); ++i) {\n if (test_suite.GetTestInfo(i)->is_reportable()) {\n if (comma) {\n *stream << \",\\n\";\n } else {\n comma = true;\n }\n OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));\n }\n }\n *stream << \"\\n\" << kIndent << \"]\\n\" << Indent(4) << \"}\";\n}\n\n// Prints a JSON summary of unit_test to output stream out.\nvoid JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,\n const UnitTest& unit_test) {\n const std::string kTestsuites = \"testsuites\";\n const std::string kIndent = Indent(2);\n *stream << \"{\\n\";\n\n OutputJsonKey(stream, kTestsuites, \"tests\", unit_test.reportable_test_count(),\n kIndent);\n OutputJsonKey(stream, kTestsuites, \"failures\", unit_test.failed_test_count(),\n kIndent);\n OutputJsonKey(stream, kTestsuites, \"disabled\",\n unit_test.reportable_disabled_test_count(), kIndent);\n OutputJsonKey(stream, kTestsuites, \"errors\", 0, kIndent);\n if (GTEST_FLAG(shuffle)) {\n OutputJsonKey(stream, kTestsuites, \"random_seed\", unit_test.random_seed(),\n kIndent);\n }\n OutputJsonKey(stream, kTestsuites, \"timestamp\",\n FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),\n kIndent);\n OutputJsonKey(stream, kTestsuites, \"time\",\n FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,\n false);\n\n *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)\n << \",\\n\";\n\n OutputJsonKey(stream, kTestsuites, \"name\", \"AllTests\", kIndent);\n *stream << kIndent << \"\\\"\" << kTestsuites << \"\\\": [\\n\";\n\n bool comma = false;\n for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {\n if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) {\n if (comma) {\n *stream << \",\\n\";\n } else {\n comma = true;\n }\n PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i));\n }\n }\n\n // If there was a test failure outside of one of the test suites (like in a\n // test environment) include that in the output.\n if (unit_test.ad_hoc_test_result().Failed()) {\n OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());\n }\n\n *stream << \"\\n\" << kIndent << \"]\\n\" << \"}\\n\";\n}\n\nvoid JsonUnitTestResultPrinter::PrintJsonTestList(\n std::ostream* stream, const std::vector& test_suites) {\n const std::string kTestsuites = \"testsuites\";\n const std::string kIndent = Indent(2);\n *stream << \"{\\n\";\n int total_tests = 0;\n for (auto test_suite : test_suites) {\n total_tests += test_suite->total_test_count();\n }\n OutputJsonKey(stream, kTestsuites, \"tests\", total_tests, kIndent);\n\n OutputJsonKey(stream, kTestsuites, \"name\", \"AllTests\", kIndent);\n *stream << kIndent << \"\\\"\" << kTestsuites << \"\\\": [\\n\";\n\n for (size_t i = 0; i < test_suites.size(); ++i) {\n if (i != 0) {\n *stream << \",\\n\";\n }\n PrintJsonTestSuite(stream, *test_suites[i]);\n }\n\n *stream << \"\\n\"\n << kIndent << \"]\\n\"\n << \"}\\n\";\n}\n// Produces a string representing the test properties in a result as\n// a JSON dictionary.\nstd::string JsonUnitTestResultPrinter::TestPropertiesAsJson(\n const TestResult& result, const std::string& indent) {\n Message attributes;\n for (int i = 0; i < result.test_property_count(); ++i) {\n const TestProperty& property = result.GetTestProperty(i);\n attributes << \",\\n\" << indent << \"\\\"\" << property.key() << \"\\\": \"\n << \"\\\"\" << EscapeJson(property.value()) << \"\\\"\";\n }\n return attributes.GetString();\n}\n\n// End JsonUnitTestResultPrinter\n\n#if GTEST_CAN_STREAM_RESULTS_\n\n// Checks if str contains '=', '&', '%' or '\\n' characters. If yes,\n// replaces them by \"%xx\" where xx is their hexadecimal value. For\n// example, replaces \"=\" with \"%3D\". This algorithm is O(strlen(str))\n// in both time and space -- important as the input str may contain an\n// arbitrarily long test failure message and stack trace.\nstd::string StreamingListener::UrlEncode(const char* str) {\n std::string result;\n result.reserve(strlen(str) + 1);\n for (char ch = *str; ch != '\\0'; ch = *++str) {\n switch (ch) {\n case '%':\n case '=':\n case '&':\n case '\\n':\n result.append(\"%\" + String::FormatByte(static_cast(ch)));\n break;\n default:\n result.push_back(ch);\n break;\n }\n }\n return result;\n}\n\nvoid StreamingListener::SocketWriter::MakeConnection() {\n GTEST_CHECK_(sockfd_ == -1)\n << \"MakeConnection() can't be called when there is already a connection.\";\n\n addrinfo hints;\n memset(&hints, 0, sizeof(hints));\n hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.\n hints.ai_socktype = SOCK_STREAM;\n addrinfo* servinfo = nullptr;\n\n // Use the getaddrinfo() to get a linked list of IP addresses for\n // the given host name.\n const int error_num = getaddrinfo(\n host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);\n if (error_num != 0) {\n GTEST_LOG_(WARNING) << \"stream_result_to: getaddrinfo() failed: \"\n << gai_strerror(error_num);\n }\n\n // Loop through all the results and connect to the first we can.\n for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr;\n cur_addr = cur_addr->ai_next) {\n sockfd_ = socket(\n cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);\n if (sockfd_ != -1) {\n // Connect the client socket to the server socket.\n if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {\n close(sockfd_);\n sockfd_ = -1;\n }\n }\n }\n\n freeaddrinfo(servinfo); // all done with this structure\n\n if (sockfd_ == -1) {\n GTEST_LOG_(WARNING) << \"stream_result_to: failed to connect to \"\n << host_name_ << \":\" << port_num_;\n }\n}\n\n// End of class Streaming Listener\n#endif // GTEST_CAN_STREAM_RESULTS__\n\n// class OsStackTraceGetter\n\nconst char* const OsStackTraceGetterInterface::kElidedFramesMarker =\n \"... \" GTEST_NAME_ \" internal frames ...\";\n\nstd::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)\n GTEST_LOCK_EXCLUDED_(mutex_) {\n#if GTEST_HAS_ABSL\n std::string result;\n\n if (max_depth <= 0) {\n return result;\n }\n\n max_depth = std::min(max_depth, kMaxStackTraceDepth);\n\n std::vector raw_stack(max_depth);\n // Skips the frames requested by the caller, plus this function.\n const int raw_stack_size =\n absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);\n\n void* caller_frame = nullptr;\n {\n MutexLock lock(&mutex_);\n caller_frame = caller_frame_;\n }\n\n for (int i = 0; i < raw_stack_size; ++i) {\n if (raw_stack[i] == caller_frame &&\n !GTEST_FLAG(show_internal_stack_frames)) {\n // Add a marker to the trace and stop adding frames.\n absl::StrAppend(&result, kElidedFramesMarker, \"\\n\");\n break;\n }\n\n char tmp[1024];\n const char* symbol = \"(unknown)\";\n if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) {\n symbol = tmp;\n }\n\n char line[1024];\n snprintf(line, sizeof(line), \" %p: %s\\n\", raw_stack[i], symbol);\n result += line;\n }\n\n return result;\n\n#else // !GTEST_HAS_ABSL\n static_cast(max_depth);\n static_cast(skip_count);\n return \"\";\n#endif // GTEST_HAS_ABSL\n}\n\nvoid OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {\n#if GTEST_HAS_ABSL\n void* caller_frame = nullptr;\n if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {\n caller_frame = nullptr;\n }\n\n MutexLock lock(&mutex_);\n caller_frame_ = caller_frame;\n#endif // GTEST_HAS_ABSL\n}\n\n// A helper class that creates the premature-exit file in its\n// constructor and deletes the file in its destructor.\nclass ScopedPrematureExitFile {\n public:\n explicit ScopedPrematureExitFile(const char* premature_exit_filepath)\n : premature_exit_filepath_(premature_exit_filepath ?\n premature_exit_filepath : \"\") {\n // If a path to the premature-exit file is specified...\n if (!premature_exit_filepath_.empty()) {\n // create the file with a single \"0\" character in it. I/O\n // errors are ignored as there's nothing better we can do and we\n // don't want to fail the test because of this.\n FILE* pfile = posix::FOpen(premature_exit_filepath, \"w\");\n fwrite(\"0\", 1, 1, pfile);\n fclose(pfile);\n }\n }\n\n ~ScopedPrematureExitFile() {\n#if !defined GTEST_OS_ESP8266\n if (!premature_exit_filepath_.empty()) {\n int retval = remove(premature_exit_filepath_.c_str());\n if (retval) {\n GTEST_LOG_(ERROR) << \"Failed to remove premature exit filepath \\\"\"\n << premature_exit_filepath_ << \"\\\" with error \"\n << retval;\n }\n }\n#endif\n }\n\n private:\n const std::string premature_exit_filepath_;\n\n GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);\n};\n\n} // namespace internal\n\n// class TestEventListeners\n\nTestEventListeners::TestEventListeners()\n : repeater_(new internal::TestEventRepeater()),\n default_result_printer_(nullptr),\n default_xml_generator_(nullptr) {}\n\nTestEventListeners::~TestEventListeners() { delete repeater_; }\n\n// Returns the standard listener responsible for the default console\n// output. Can be removed from the listeners list to shut down default\n// console output. Note that removing this object from the listener list\n// with Release transfers its ownership to the user.\nvoid TestEventListeners::Append(TestEventListener* listener) {\n repeater_->Append(listener);\n}\n\n// Removes the given event listener from the list and returns it. It then\n// becomes the caller's responsibility to delete the listener. Returns\n// NULL if the listener is not found in the list.\nTestEventListener* TestEventListeners::Release(TestEventListener* listener) {\n if (listener == default_result_printer_)\n default_result_printer_ = nullptr;\n else if (listener == default_xml_generator_)\n default_xml_generator_ = nullptr;\n return repeater_->Release(listener);\n}\n\n// Returns repeater that broadcasts the TestEventListener events to all\n// subscribers.\nTestEventListener* TestEventListeners::repeater() { return repeater_; }\n\n// Sets the default_result_printer attribute to the provided listener.\n// The listener is also added to the listener list and previous\n// default_result_printer is removed from it and deleted. The listener can\n// also be NULL in which case it will not be added to the list. Does\n// nothing if the previous and the current listener objects are the same.\nvoid TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {\n if (default_result_printer_ != listener) {\n // It is an error to pass this method a listener that is already in the\n // list.\n delete Release(default_result_printer_);\n default_result_printer_ = listener;\n if (listener != nullptr) Append(listener);\n }\n}\n\n// Sets the default_xml_generator attribute to the provided listener. The\n// listener is also added to the listener list and previous\n// default_xml_generator is removed from it and deleted. The listener can\n// also be NULL in which case it will not be added to the list. Does\n// nothing if the previous and the current listener objects are the same.\nvoid TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {\n if (default_xml_generator_ != listener) {\n // It is an error to pass this method a listener that is already in the\n // list.\n delete Release(default_xml_generator_);\n default_xml_generator_ = listener;\n if (listener != nullptr) Append(listener);\n }\n}\n\n// Controls whether events will be forwarded by the repeater to the\n// listeners in the list.\nbool TestEventListeners::EventForwardingEnabled() const {\n return repeater_->forwarding_enabled();\n}\n\nvoid TestEventListeners::SuppressEventForwarding() {\n repeater_->set_forwarding_enabled(false);\n}\n\n// class UnitTest\n\n// Gets the singleton UnitTest object. The first time this method is\n// called, a UnitTest object is constructed and returned. Consecutive\n// calls will return the same object.\n//\n// We don't protect this under mutex_ as a user is not supposed to\n// call this before main() starts, from which point on the return\n// value will never change.\nUnitTest* UnitTest::GetInstance() {\n // CodeGear C++Builder insists on a public destructor for the\n // default implementation. Use this implementation to keep good OO\n // design with private destructor.\n\n#if defined(__BORLANDC__)\n static UnitTest* const instance = new UnitTest;\n return instance;\n#else\n static UnitTest instance;\n return &instance;\n#endif // defined(__BORLANDC__)\n}\n\n// Gets the number of successful test suites.\nint UnitTest::successful_test_suite_count() const {\n return impl()->successful_test_suite_count();\n}\n\n// Gets the number of failed test suites.\nint UnitTest::failed_test_suite_count() const {\n return impl()->failed_test_suite_count();\n}\n\n// Gets the number of all test suites.\nint UnitTest::total_test_suite_count() const {\n return impl()->total_test_suite_count();\n}\n\n// Gets the number of all test suites that contain at least one test\n// that should run.\nint UnitTest::test_suite_to_run_count() const {\n return impl()->test_suite_to_run_count();\n}\n\n// Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\nint UnitTest::successful_test_case_count() const {\n return impl()->successful_test_suite_count();\n}\nint UnitTest::failed_test_case_count() const {\n return impl()->failed_test_suite_count();\n}\nint UnitTest::total_test_case_count() const {\n return impl()->total_test_suite_count();\n}\nint UnitTest::test_case_to_run_count() const {\n return impl()->test_suite_to_run_count();\n}\n#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n// Gets the number of successful tests.\nint UnitTest::successful_test_count() const {\n return impl()->successful_test_count();\n}\n\n// Gets the number of skipped tests.\nint UnitTest::skipped_test_count() const {\n return impl()->skipped_test_count();\n}\n\n// Gets the number of failed tests.\nint UnitTest::failed_test_count() const { return impl()->failed_test_count(); }\n\n// Gets the number of disabled tests that will be reported in the XML report.\nint UnitTest::reportable_disabled_test_count() const {\n return impl()->reportable_disabled_test_count();\n}\n\n// Gets the number of disabled tests.\nint UnitTest::disabled_test_count() const {\n return impl()->disabled_test_count();\n}\n\n// Gets the number of tests to be printed in the XML report.\nint UnitTest::reportable_test_count() const {\n return impl()->reportable_test_count();\n}\n\n// Gets the number of all tests.\nint UnitTest::total_test_count() const { return impl()->total_test_count(); }\n\n// Gets the number of tests that should run.\nint UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }\n\n// Gets the time of the test program start, in ms from the start of the\n// UNIX epoch.\ninternal::TimeInMillis UnitTest::start_timestamp() const {\n return impl()->start_timestamp();\n}\n\n// Gets the elapsed time, in milliseconds.\ninternal::TimeInMillis UnitTest::elapsed_time() const {\n return impl()->elapsed_time();\n}\n\n// Returns true if and only if the unit test passed (i.e. all test suites\n// passed).\nbool UnitTest::Passed() const { return impl()->Passed(); }\n\n// Returns true if and only if the unit test failed (i.e. some test suite\n// failed or something outside of all tests failed).\nbool UnitTest::Failed() const { return impl()->Failed(); }\n\n// Gets the i-th test suite among all the test suites. i can range from 0 to\n// total_test_suite_count() - 1. If i is not in that range, returns NULL.\nconst TestSuite* UnitTest::GetTestSuite(int i) const {\n return impl()->GetTestSuite(i);\n}\n\n// Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\nconst TestCase* UnitTest::GetTestCase(int i) const {\n return impl()->GetTestCase(i);\n}\n#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n// Returns the TestResult containing information on test failures and\n// properties logged outside of individual test suites.\nconst TestResult& UnitTest::ad_hoc_test_result() const {\n return *impl()->ad_hoc_test_result();\n}\n\n// Gets the i-th test suite among all the test suites. i can range from 0 to\n// total_test_suite_count() - 1. If i is not in that range, returns NULL.\nTestSuite* UnitTest::GetMutableTestSuite(int i) {\n return impl()->GetMutableSuiteCase(i);\n}\n\n// Returns the list of event listeners that can be used to track events\n// inside Google Test.\nTestEventListeners& UnitTest::listeners() {\n return *impl()->listeners();\n}\n\n// Registers and returns a global test environment. When a test\n// program is run, all global test environments will be set-up in the\n// order they were registered. After all tests in the program have\n// finished, all global test environments will be torn-down in the\n// *reverse* order they were registered.\n//\n// The UnitTest object takes ownership of the given environment.\n//\n// We don't protect this under mutex_, as we only support calling it\n// from the main thread.\nEnvironment* UnitTest::AddEnvironment(Environment* env) {\n if (env == nullptr) {\n return nullptr;\n }\n\n impl_->environments().push_back(env);\n return env;\n}\n\n// Adds a TestPartResult to the current TestResult object. All Google Test\n// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call\n// this to report their results. The user code should use the\n// assertion macros instead of calling this directly.\nvoid UnitTest::AddTestPartResult(\n TestPartResult::Type result_type,\n const char* file_name,\n int line_number,\n const std::string& message,\n const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {\n Message msg;\n msg << message;\n\n internal::MutexLock lock(&mutex_);\n if (impl_->gtest_trace_stack().size() > 0) {\n msg << \"\\n\" << GTEST_NAME_ << \" trace:\";\n\n for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) {\n const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];\n msg << \"\\n\" << internal::FormatFileLocation(trace.file, trace.line)\n << \" \" << trace.message;\n }\n }\n\n if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) {\n msg << internal::kStackTraceMarker << os_stack_trace;\n }\n\n const TestPartResult result = TestPartResult(\n result_type, file_name, line_number, msg.GetString().c_str());\n impl_->GetTestPartResultReporterForCurrentThread()->\n ReportTestPartResult(result);\n\n if (result_type != TestPartResult::kSuccess &&\n result_type != TestPartResult::kSkip) {\n // gtest_break_on_failure takes precedence over\n // gtest_throw_on_failure. This allows a user to set the latter\n // in the code (perhaps in order to use Google Test assertions\n // with another testing framework) and specify the former on the\n // command line for debugging.\n if (GTEST_FLAG(break_on_failure)) {\n#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT\n // Using DebugBreak on Windows allows gtest to still break into a debugger\n // when a failure happens and both the --gtest_break_on_failure and\n // the --gtest_catch_exceptions flags are specified.\n DebugBreak();\n#elif (!defined(__native_client__)) && \\\n ((defined(__clang__) || defined(__GNUC__)) && \\\n (defined(__x86_64__) || defined(__i386__)))\n // with clang/gcc we can achieve the same effect on x86 by invoking int3\n asm(\"int3\");\n#else\n // Dereference nullptr through a volatile pointer to prevent the compiler\n // from removing. We use this rather than abort() or __builtin_trap() for\n // portability: some debuggers don't correctly trap abort().\n *static_cast(nullptr) = 1;\n#endif // GTEST_OS_WINDOWS\n } else if (GTEST_FLAG(throw_on_failure)) {\n#if GTEST_HAS_EXCEPTIONS\n throw internal::GoogleTestFailureException(result);\n#else\n // We cannot call abort() as it generates a pop-up in debug mode\n // that cannot be suppressed in VC 7.1 or below.\n exit(1);\n#endif\n }\n }\n}\n\n// Adds a TestProperty to the current TestResult object when invoked from\n// inside a test, to current TestSuite's ad_hoc_test_result_ when invoked\n// from SetUpTestSuite or TearDownTestSuite, or to the global property set\n// when invoked elsewhere. If the result already contains a property with\n// the same key, the value will be updated.\nvoid UnitTest::RecordProperty(const std::string& key,\n const std::string& value) {\n impl_->RecordProperty(TestProperty(key, value));\n}\n\n// Runs all tests in this UnitTest object and prints the result.\n// Returns 0 if successful, or 1 otherwise.\n//\n// We don't protect this under mutex_, as we only support calling it\n// from the main thread.\nint UnitTest::Run() {\n const bool in_death_test_child_process =\n internal::GTEST_FLAG(internal_run_death_test).length() > 0;\n\n // Google Test implements this protocol for catching that a test\n // program exits before returning control to Google Test:\n //\n // 1. Upon start, Google Test creates a file whose absolute path\n // is specified by the environment variable\n // TEST_PREMATURE_EXIT_FILE.\n // 2. When Google Test has finished its work, it deletes the file.\n //\n // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before\n // running a Google-Test-based test program and check the existence\n // of the file at the end of the test execution to see if it has\n // exited prematurely.\n\n // If we are in the child process of a death test, don't\n // create/delete the premature exit file, as doing so is unnecessary\n // and will confuse the parent process. Otherwise, create/delete\n // the file upon entering/leaving this function. If the program\n // somehow exits before this function has a chance to return, the\n // premature-exit file will be left undeleted, causing a test runner\n // that understands the premature-exit-file protocol to report the\n // test as having failed.\n const internal::ScopedPrematureExitFile premature_exit_file(\n in_death_test_child_process\n ? nullptr\n : internal::posix::GetEnv(\"TEST_PREMATURE_EXIT_FILE\"));\n\n // Captures the value of GTEST_FLAG(catch_exceptions). This value will be\n // used for the duration of the program.\n impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));\n\n#if GTEST_OS_WINDOWS\n // Either the user wants Google Test to catch exceptions thrown by the\n // tests or this is executing in the context of death test child\n // process. In either case the user does not want to see pop-up dialogs\n // about crashes - they are expected.\n if (impl()->catch_exceptions() || in_death_test_child_process) {\n# if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT\n // SetErrorMode doesn't exist on CE.\n SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |\n SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);\n# endif // !GTEST_OS_WINDOWS_MOBILE\n\n# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE\n // Death test children can be terminated with _abort(). On Windows,\n // _abort() can show a dialog with a warning message. This forces the\n // abort message to go to stderr instead.\n _set_error_mode(_OUT_TO_STDERR);\n# endif\n\n# if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE\n // In the debug version, Visual Studio pops up a separate dialog\n // offering a choice to debug the aborted program. We need to suppress\n // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement\n // executed. Google Test will notify the user of any unexpected\n // failure via stderr.\n if (!GTEST_FLAG(break_on_failure))\n _set_abort_behavior(\n 0x0, // Clear the following flags:\n _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.\n\n // In debug mode, the Windows CRT can crash with an assertion over invalid\n // input (e.g. passing an invalid file descriptor). The default handling\n // for these assertions is to pop up a dialog and wait for user input.\n // Instead ask the CRT to dump such assertions to stderr non-interactively.\n if (!IsDebuggerPresent()) {\n (void)_CrtSetReportMode(_CRT_ASSERT,\n _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);\n (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);\n }\n# endif\n }\n#endif // GTEST_OS_WINDOWS\n\n return internal::HandleExceptionsInMethodIfSupported(\n impl(),\n &internal::UnitTestImpl::RunAllTests,\n \"auxiliary test code (environments or event listeners)\") ? 0 : 1;\n}\n\n// Returns the working directory when the first TEST() or TEST_F() was\n// executed.\nconst char* UnitTest::original_working_dir() const {\n return impl_->original_working_dir_.c_str();\n}\n\n// Returns the TestSuite object for the test that's currently running,\n// or NULL if no test is running.\nconst TestSuite* UnitTest::current_test_suite() const\n GTEST_LOCK_EXCLUDED_(mutex_) {\n internal::MutexLock lock(&mutex_);\n return impl_->current_test_suite();\n}\n\n// Legacy API is still available but deprecated\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\nconst TestCase* UnitTest::current_test_case() const\n GTEST_LOCK_EXCLUDED_(mutex_) {\n internal::MutexLock lock(&mutex_);\n return impl_->current_test_suite();\n}\n#endif\n\n// Returns the TestInfo object for the test that's currently running,\n// or NULL if no test is running.\nconst TestInfo* UnitTest::current_test_info() const\n GTEST_LOCK_EXCLUDED_(mutex_) {\n internal::MutexLock lock(&mutex_);\n return impl_->current_test_info();\n}\n\n// Returns the random seed used at the start of the current test run.\nint UnitTest::random_seed() const { return impl_->random_seed(); }\n\n// Returns ParameterizedTestSuiteRegistry object used to keep track of\n// value-parameterized tests and instantiate and register them.\ninternal::ParameterizedTestSuiteRegistry&\nUnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) {\n return impl_->parameterized_test_registry();\n}\n\n// Creates an empty UnitTest.\nUnitTest::UnitTest() {\n impl_ = new internal::UnitTestImpl(this);\n}\n\n// Destructor of UnitTest.\nUnitTest::~UnitTest() {\n delete impl_;\n}\n\n// Pushes a trace defined by SCOPED_TRACE() on to the per-thread\n// Google Test trace stack.\nvoid UnitTest::PushGTestTrace(const internal::TraceInfo& trace)\n GTEST_LOCK_EXCLUDED_(mutex_) {\n internal::MutexLock lock(&mutex_);\n impl_->gtest_trace_stack().push_back(trace);\n}\n\n// Pops a trace from the per-thread Google Test trace stack.\nvoid UnitTest::PopGTestTrace()\n GTEST_LOCK_EXCLUDED_(mutex_) {\n internal::MutexLock lock(&mutex_);\n impl_->gtest_trace_stack().pop_back();\n}\n\nnamespace internal {\n\nUnitTestImpl::UnitTestImpl(UnitTest* parent)\n : parent_(parent),\n GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)\n default_global_test_part_result_reporter_(this),\n default_per_thread_test_part_result_reporter_(this),\n GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_(\n &default_global_test_part_result_reporter_),\n per_thread_test_part_result_reporter_(\n &default_per_thread_test_part_result_reporter_),\n parameterized_test_registry_(),\n parameterized_tests_registered_(false),\n last_death_test_suite_(-1),\n current_test_suite_(nullptr),\n current_test_info_(nullptr),\n ad_hoc_test_result_(),\n os_stack_trace_getter_(nullptr),\n post_flag_parse_init_performed_(false),\n random_seed_(0), // Will be overridden by the flag before first use.\n random_(0), // Will be reseeded before first use.\n start_timestamp_(0),\n elapsed_time_(0),\n#if GTEST_HAS_DEATH_TEST\n death_test_factory_(new DefaultDeathTestFactory),\n#endif\n // Will be overridden by the flag before first use.\n catch_exceptions_(false) {\n listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);\n}\n\nUnitTestImpl::~UnitTestImpl() {\n // Deletes every TestSuite.\n ForEach(test_suites_, internal::Delete);\n\n // Deletes every Environment.\n ForEach(environments_, internal::Delete);\n\n delete os_stack_trace_getter_;\n}\n\n// Adds a TestProperty to the current TestResult object when invoked in a\n// context of a test, to current test suite's ad_hoc_test_result when invoke\n// from SetUpTestSuite/TearDownTestSuite, or to the global property set\n// otherwise. If the result already contains a property with the same key,\n// the value will be updated.\nvoid UnitTestImpl::RecordProperty(const TestProperty& test_property) {\n std::string xml_element;\n TestResult* test_result; // TestResult appropriate for property recording.\n\n if (current_test_info_ != nullptr) {\n xml_element = \"testcase\";\n test_result = &(current_test_info_->result_);\n } else if (current_test_suite_ != nullptr) {\n xml_element = \"testsuite\";\n test_result = &(current_test_suite_->ad_hoc_test_result_);\n } else {\n xml_element = \"testsuites\";\n test_result = &ad_hoc_test_result_;\n }\n test_result->RecordProperty(xml_element, test_property);\n}\n\n#if GTEST_HAS_DEATH_TEST\n// Disables event forwarding if the control is currently in a death test\n// subprocess. Must not be called before InitGoogleTest.\nvoid UnitTestImpl::SuppressTestEventsIfInSubprocess() {\n if (internal_run_death_test_flag_.get() != nullptr)\n listeners()->SuppressEventForwarding();\n}\n#endif // GTEST_HAS_DEATH_TEST\n\n// Initializes event listeners performing XML output as specified by\n// UnitTestOptions. Must not be called before InitGoogleTest.\nvoid UnitTestImpl::ConfigureXmlOutput() {\n const std::string& output_format = UnitTestOptions::GetOutputFormat();\n if (output_format == \"xml\") {\n listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(\n UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));\n } else if (output_format == \"json\") {\n listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(\n UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));\n } else if (output_format != \"\") {\n GTEST_LOG_(WARNING) << \"WARNING: unrecognized output format \\\"\"\n << output_format << \"\\\" ignored.\";\n }\n}\n\n#if GTEST_CAN_STREAM_RESULTS_\n// Initializes event listeners for streaming test results in string form.\n// Must not be called before InitGoogleTest.\nvoid UnitTestImpl::ConfigureStreamingOutput() {\n const std::string& target = GTEST_FLAG(stream_result_to);\n if (!target.empty()) {\n const size_t pos = target.find(':');\n if (pos != std::string::npos) {\n listeners()->Append(new StreamingListener(target.substr(0, pos),\n target.substr(pos+1)));\n } else {\n GTEST_LOG_(WARNING) << \"unrecognized streaming target \\\"\" << target\n << \"\\\" ignored.\";\n }\n }\n}\n#endif // GTEST_CAN_STREAM_RESULTS_\n\n// Performs initialization dependent upon flag values obtained in\n// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to\n// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest\n// this function is also called from RunAllTests. Since this function can be\n// called more than once, it has to be idempotent.\nvoid UnitTestImpl::PostFlagParsingInit() {\n // Ensures that this function does not execute more than once.\n if (!post_flag_parse_init_performed_) {\n post_flag_parse_init_performed_ = true;\n\n#if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)\n // Register to send notifications about key process state changes.\n listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());\n#endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)\n\n#if GTEST_HAS_DEATH_TEST\n InitDeathTestSubprocessControlInfo();\n SuppressTestEventsIfInSubprocess();\n#endif // GTEST_HAS_DEATH_TEST\n\n // Registers parameterized tests. This makes parameterized tests\n // available to the UnitTest reflection API without running\n // RUN_ALL_TESTS.\n RegisterParameterizedTests();\n\n // Configures listeners for XML output. This makes it possible for users\n // to shut down the default XML output before invoking RUN_ALL_TESTS.\n ConfigureXmlOutput();\n\n if (GTEST_FLAG(brief)) {\n listeners()->SetDefaultResultPrinter(new BriefUnitTestResultPrinter);\n }\n\n#if GTEST_CAN_STREAM_RESULTS_\n // Configures listeners for streaming test results to the specified server.\n ConfigureStreamingOutput();\n#endif // GTEST_CAN_STREAM_RESULTS_\n\n#if GTEST_HAS_ABSL\n if (GTEST_FLAG(install_failure_signal_handler)) {\n absl::FailureSignalHandlerOptions options;\n absl::InstallFailureSignalHandler(options);\n }\n#endif // GTEST_HAS_ABSL\n }\n}\n\n// A predicate that checks the name of a TestSuite against a known\n// value.\n//\n// This is used for implementation of the UnitTest class only. We put\n// it in the anonymous namespace to prevent polluting the outer\n// namespace.\n//\n// TestSuiteNameIs is copyable.\nclass TestSuiteNameIs {\n public:\n // Constructor.\n explicit TestSuiteNameIs(const std::string& name) : name_(name) {}\n\n // Returns true if and only if the name of test_suite matches name_.\n bool operator()(const TestSuite* test_suite) const {\n return test_suite != nullptr &&\n strcmp(test_suite->name(), name_.c_str()) == 0;\n }\n\n private:\n std::string name_;\n};\n\n// Finds and returns a TestSuite with the given name. If one doesn't\n// exist, creates one and returns it. It's the CALLER'S\n// RESPONSIBILITY to ensure that this function is only called WHEN THE\n// TESTS ARE NOT SHUFFLED.\n//\n// Arguments:\n//\n// test_suite_name: name of the test suite\n// type_param: the name of the test suite's type parameter, or NULL if\n// this is not a typed or a type-parameterized test suite.\n// set_up_tc: pointer to the function that sets up the test suite\n// tear_down_tc: pointer to the function that tears down the test suite\nTestSuite* UnitTestImpl::GetTestSuite(\n const char* test_suite_name, const char* type_param,\n internal::SetUpTestSuiteFunc set_up_tc,\n internal::TearDownTestSuiteFunc tear_down_tc) {\n // Can we find a TestSuite with the given name?\n const auto test_suite =\n std::find_if(test_suites_.rbegin(), test_suites_.rend(),\n TestSuiteNameIs(test_suite_name));\n\n if (test_suite != test_suites_.rend()) return *test_suite;\n\n // No. Let's create one.\n auto* const new_test_suite =\n new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);\n\n // Is this a death test suite?\n if (internal::UnitTestOptions::MatchesFilter(test_suite_name,\n kDeathTestSuiteFilter)) {\n // Yes. Inserts the test suite after the last death test suite\n // defined so far. This only works when the test suites haven't\n // been shuffled. Otherwise we may end up running a death test\n // after a non-death test.\n ++last_death_test_suite_;\n test_suites_.insert(test_suites_.begin() + last_death_test_suite_,\n new_test_suite);\n } else {\n // No. Appends to the end of the list.\n test_suites_.push_back(new_test_suite);\n }\n\n test_suite_indices_.push_back(static_cast(test_suite_indices_.size()));\n return new_test_suite;\n}\n\n// Helpers for setting up / tearing down the given environment. They\n// are for use in the ForEach() function.\nstatic void SetUpEnvironment(Environment* env) { env->SetUp(); }\nstatic void TearDownEnvironment(Environment* env) { env->TearDown(); }\n\n// Runs all tests in this UnitTest object, prints the result, and\n// returns true if all tests are successful. If any exception is\n// thrown during a test, the test is considered to be failed, but the\n// rest of the tests will still be run.\n//\n// When parameterized tests are enabled, it expands and registers\n// parameterized tests first in RegisterParameterizedTests().\n// All other functions called from RunAllTests() may safely assume that\n// parameterized tests are ready to be counted and run.\nbool UnitTestImpl::RunAllTests() {\n // True if and only if Google Test is initialized before RUN_ALL_TESTS() is\n // called.\n const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();\n\n // Do not run any test if the --help flag was specified.\n if (g_help_flag)\n return true;\n\n // Repeats the call to the post-flag parsing initialization in case the\n // user didn't call InitGoogleTest.\n PostFlagParsingInit();\n\n // Even if sharding is not on, test runners may want to use the\n // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding\n // protocol.\n internal::WriteToShardStatusFileIfNeeded();\n\n // True if and only if we are in a subprocess for running a thread-safe-style\n // death test.\n bool in_subprocess_for_death_test = false;\n\n#if GTEST_HAS_DEATH_TEST\n in_subprocess_for_death_test =\n (internal_run_death_test_flag_.get() != nullptr);\n# if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)\n if (in_subprocess_for_death_test) {\n GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();\n }\n# endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)\n#endif // GTEST_HAS_DEATH_TEST\n\n const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,\n in_subprocess_for_death_test);\n\n // Compares the full test names with the filter to decide which\n // tests to run.\n const bool has_tests_to_run = FilterTests(should_shard\n ? HONOR_SHARDING_PROTOCOL\n : IGNORE_SHARDING_PROTOCOL) > 0;\n\n // Lists the tests and exits if the --gtest_list_tests flag was specified.\n if (GTEST_FLAG(list_tests)) {\n // This must be called *after* FilterTests() has been called.\n ListTestsMatchingFilter();\n return true;\n }\n\n random_seed_ = GTEST_FLAG(shuffle) ?\n GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;\n\n // True if and only if at least one test has failed.\n bool failed = false;\n\n TestEventListener* repeater = listeners()->repeater();\n\n start_timestamp_ = GetTimeInMillis();\n repeater->OnTestProgramStart(*parent_);\n\n // How many times to repeat the tests? We don't want to repeat them\n // when we are inside the subprocess of a death test.\n const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);\n // Repeats forever if the repeat count is negative.\n const bool gtest_repeat_forever = repeat < 0;\n for (int i = 0; gtest_repeat_forever || i != repeat; i++) {\n // We want to preserve failures generated by ad-hoc test\n // assertions executed before RUN_ALL_TESTS().\n ClearNonAdHocTestResult();\n\n Timer timer;\n\n // Shuffles test suites and tests if requested.\n if (has_tests_to_run && GTEST_FLAG(shuffle)) {\n random()->Reseed(static_cast(random_seed_));\n // This should be done before calling OnTestIterationStart(),\n // such that a test event listener can see the actual test order\n // in the event.\n ShuffleTests();\n }\n\n // Tells the unit test event listeners that the tests are about to start.\n repeater->OnTestIterationStart(*parent_, i);\n\n // Runs each test suite if there is at least one test to run.\n if (has_tests_to_run) {\n // Sets up all environments beforehand.\n repeater->OnEnvironmentsSetUpStart(*parent_);\n ForEach(environments_, SetUpEnvironment);\n repeater->OnEnvironmentsSetUpEnd(*parent_);\n\n // Runs the tests only if there was no fatal failure or skip triggered\n // during global set-up.\n if (Test::IsSkipped()) {\n // Emit diagnostics when global set-up calls skip, as it will not be\n // emitted by default.\n TestResult& test_result =\n *internal::GetUnitTestImpl()->current_test_result();\n for (int j = 0; j < test_result.total_part_count(); ++j) {\n const TestPartResult& test_part_result =\n test_result.GetTestPartResult(j);\n if (test_part_result.type() == TestPartResult::kSkip) {\n const std::string& result = test_part_result.message();\n printf(\"%s\\n\", result.c_str());\n }\n }\n fflush(stdout);\n } else if (!Test::HasFatalFailure()) {\n for (int test_index = 0; test_index < total_test_suite_count();\n test_index++) {\n GetMutableSuiteCase(test_index)->Run();\n if (GTEST_FLAG(fail_fast) &&\n GetMutableSuiteCase(test_index)->Failed()) {\n for (int j = test_index + 1; j < total_test_suite_count(); j++) {\n GetMutableSuiteCase(j)->Skip();\n }\n break;\n }\n }\n } else if (Test::HasFatalFailure()) {\n // If there was a fatal failure during the global setup then we know we\n // aren't going to run any tests. Explicitly mark all of the tests as\n // skipped to make this obvious in the output.\n for (int test_index = 0; test_index < total_test_suite_count();\n test_index++) {\n GetMutableSuiteCase(test_index)->Skip();\n }\n }\n\n // Tears down all environments in reverse order afterwards.\n repeater->OnEnvironmentsTearDownStart(*parent_);\n std::for_each(environments_.rbegin(), environments_.rend(),\n TearDownEnvironment);\n repeater->OnEnvironmentsTearDownEnd(*parent_);\n }\n\n elapsed_time_ = timer.Elapsed();\n\n // Tells the unit test event listener that the tests have just finished.\n repeater->OnTestIterationEnd(*parent_, i);\n\n // Gets the result and clears it.\n if (!Passed()) {\n failed = true;\n }\n\n // Restores the original test order after the iteration. This\n // allows the user to quickly repro a failure that happens in the\n // N-th iteration without repeating the first (N - 1) iterations.\n // This is not enclosed in \"if (GTEST_FLAG(shuffle)) { ... }\", in\n // case the user somehow changes the value of the flag somewhere\n // (it's always safe to unshuffle the tests).\n UnshuffleTests();\n\n if (GTEST_FLAG(shuffle)) {\n // Picks a new random seed for each iteration.\n random_seed_ = GetNextRandomSeed(random_seed_);\n }\n }\n\n repeater->OnTestProgramEnd(*parent_);\n\n if (!gtest_is_initialized_before_run_all_tests) {\n ColoredPrintf(\n GTestColor::kRed,\n \"\\nIMPORTANT NOTICE - DO NOT IGNORE:\\n\"\n \"This test program did NOT call \" GTEST_INIT_GOOGLE_TEST_NAME_\n \"() before calling RUN_ALL_TESTS(). This is INVALID. Soon \" GTEST_NAME_\n \" will start to enforce the valid usage. \"\n \"Please fix it ASAP, or IT WILL START TO FAIL.\\n\"); // NOLINT\n#if GTEST_FOR_GOOGLE_\n ColoredPrintf(GTestColor::kRed,\n \"For more details, see http://wiki/Main/ValidGUnitMain.\\n\");\n#endif // GTEST_FOR_GOOGLE_\n }\n\n return !failed;\n}\n\n// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file\n// if the variable is present. If a file already exists at this location, this\n// function will write over it. If the variable is present, but the file cannot\n// be created, prints an error and exits.\nvoid WriteToShardStatusFileIfNeeded() {\n const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);\n if (test_shard_file != nullptr) {\n FILE* const file = posix::FOpen(test_shard_file, \"w\");\n if (file == nullptr) {\n ColoredPrintf(GTestColor::kRed,\n \"Could not write to the test shard status file \\\"%s\\\" \"\n \"specified by the %s environment variable.\\n\",\n test_shard_file, kTestShardStatusFile);\n fflush(stdout);\n exit(EXIT_FAILURE);\n }\n fclose(file);\n }\n}\n\n// Checks whether sharding is enabled by examining the relevant\n// environment variable values. If the variables are present,\n// but inconsistent (i.e., shard_index >= total_shards), prints\n// an error and exits. If in_subprocess_for_death_test, sharding is\n// disabled because it must only be applied to the original test\n// process. Otherwise, we could filter out death tests we intended to execute.\nbool ShouldShard(const char* total_shards_env,\n const char* shard_index_env,\n bool in_subprocess_for_death_test) {\n if (in_subprocess_for_death_test) {\n return false;\n }\n\n const int32_t total_shards = Int32FromEnvOrDie(total_shards_env, -1);\n const int32_t shard_index = Int32FromEnvOrDie(shard_index_env, -1);\n\n if (total_shards == -1 && shard_index == -1) {\n return false;\n } else if (total_shards == -1 && shard_index != -1) {\n const Message msg = Message()\n << \"Invalid environment variables: you have \"\n << kTestShardIndex << \" = \" << shard_index\n << \", but have left \" << kTestTotalShards << \" unset.\\n\";\n ColoredPrintf(GTestColor::kRed, \"%s\", msg.GetString().c_str());\n fflush(stdout);\n exit(EXIT_FAILURE);\n } else if (total_shards != -1 && shard_index == -1) {\n const Message msg = Message()\n << \"Invalid environment variables: you have \"\n << kTestTotalShards << \" = \" << total_shards\n << \", but have left \" << kTestShardIndex << \" unset.\\n\";\n ColoredPrintf(GTestColor::kRed, \"%s\", msg.GetString().c_str());\n fflush(stdout);\n exit(EXIT_FAILURE);\n } else if (shard_index < 0 || shard_index >= total_shards) {\n const Message msg = Message()\n << \"Invalid environment variables: we require 0 <= \"\n << kTestShardIndex << \" < \" << kTestTotalShards\n << \", but you have \" << kTestShardIndex << \"=\" << shard_index\n << \", \" << kTestTotalShards << \"=\" << total_shards << \".\\n\";\n ColoredPrintf(GTestColor::kRed, \"%s\", msg.GetString().c_str());\n fflush(stdout);\n exit(EXIT_FAILURE);\n }\n\n return total_shards > 1;\n}\n\n// Parses the environment variable var as an Int32. If it is unset,\n// returns default_val. If it is not an Int32, prints an error\n// and aborts.\nint32_t Int32FromEnvOrDie(const char* var, int32_t default_val) {\n const char* str_val = posix::GetEnv(var);\n if (str_val == nullptr) {\n return default_val;\n }\n\n int32_t result;\n if (!ParseInt32(Message() << \"The value of environment variable \" << var,\n str_val, &result)) {\n exit(EXIT_FAILURE);\n }\n return result;\n}\n\n// Given the total number of shards, the shard index, and the test id,\n// returns true if and only if the test should be run on this shard. The test id\n// is some arbitrary but unique non-negative integer assigned to each test\n// method. Assumes that 0 <= shard_index < total_shards.\nbool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {\n return (test_id % total_shards) == shard_index;\n}\n\n// Compares the name of each test with the user-specified filter to\n// decide whether the test should be run, then records the result in\n// each TestSuite and TestInfo object.\n// If shard_tests == true, further filters tests based on sharding\n// variables in the environment - see\n// https://github.com/google/googletest/blob/master/googletest/docs/advanced.md\n// . Returns the number of tests that should run.\nint UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {\n const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?\n Int32FromEnvOrDie(kTestTotalShards, -1) : -1;\n const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?\n Int32FromEnvOrDie(kTestShardIndex, -1) : -1;\n\n // num_runnable_tests are the number of tests that will\n // run across all shards (i.e., match filter and are not disabled).\n // num_selected_tests are the number of tests to be run on\n // this shard.\n int num_runnable_tests = 0;\n int num_selected_tests = 0;\n for (auto* test_suite : test_suites_) {\n const std::string& test_suite_name = test_suite->name();\n test_suite->set_should_run(false);\n\n for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {\n TestInfo* const test_info = test_suite->test_info_list()[j];\n const std::string test_name(test_info->name());\n // A test is disabled if test suite name or test name matches\n // kDisableTestFilter.\n const bool is_disabled = internal::UnitTestOptions::MatchesFilter(\n test_suite_name, kDisableTestFilter) ||\n internal::UnitTestOptions::MatchesFilter(\n test_name, kDisableTestFilter);\n test_info->is_disabled_ = is_disabled;\n\n const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest(\n test_suite_name, test_name);\n test_info->matches_filter_ = matches_filter;\n\n const bool is_runnable =\n (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&\n matches_filter;\n\n const bool is_in_another_shard =\n shard_tests != IGNORE_SHARDING_PROTOCOL &&\n !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);\n test_info->is_in_another_shard_ = is_in_another_shard;\n const bool is_selected = is_runnable && !is_in_another_shard;\n\n num_runnable_tests += is_runnable;\n num_selected_tests += is_selected;\n\n test_info->should_run_ = is_selected;\n test_suite->set_should_run(test_suite->should_run() || is_selected);\n }\n }\n return num_selected_tests;\n}\n\n// Prints the given C-string on a single line by replacing all '\\n'\n// characters with string \"\\\\n\". If the output takes more than\n// max_length characters, only prints the first max_length characters\n// and \"...\".\nstatic void PrintOnOneLine(const char* str, int max_length) {\n if (str != nullptr) {\n for (int i = 0; *str != '\\0'; ++str) {\n if (i >= max_length) {\n printf(\"...\");\n break;\n }\n if (*str == '\\n') {\n printf(\"\\\\n\");\n i += 2;\n } else {\n printf(\"%c\", *str);\n ++i;\n }\n }\n }\n}\n\n// Prints the names of the tests matching the user-specified filter flag.\nvoid UnitTestImpl::ListTestsMatchingFilter() {\n // Print at most this many characters for each type/value parameter.\n const int kMaxParamLength = 250;\n\n for (auto* test_suite : test_suites_) {\n bool printed_test_suite_name = false;\n\n for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {\n const TestInfo* const test_info = test_suite->test_info_list()[j];\n if (test_info->matches_filter_) {\n if (!printed_test_suite_name) {\n printed_test_suite_name = true;\n printf(\"%s.\", test_suite->name());\n if (test_suite->type_param() != nullptr) {\n printf(\" # %s = \", kTypeParamLabel);\n // We print the type parameter on a single line to make\n // the output easy to parse by a program.\n PrintOnOneLine(test_suite->type_param(), kMaxParamLength);\n }\n printf(\"\\n\");\n }\n printf(\" %s\", test_info->name());\n if (test_info->value_param() != nullptr) {\n printf(\" # %s = \", kValueParamLabel);\n // We print the value parameter on a single line to make the\n // output easy to parse by a program.\n PrintOnOneLine(test_info->value_param(), kMaxParamLength);\n }\n printf(\"\\n\");\n }\n }\n }\n fflush(stdout);\n const std::string& output_format = UnitTestOptions::GetOutputFormat();\n if (output_format == \"xml\" || output_format == \"json\") {\n FILE* fileout = OpenFileForWriting(\n UnitTestOptions::GetAbsolutePathToOutputFile().c_str());\n std::stringstream stream;\n if (output_format == \"xml\") {\n XmlUnitTestResultPrinter(\n UnitTestOptions::GetAbsolutePathToOutputFile().c_str())\n .PrintXmlTestsList(&stream, test_suites_);\n } else if (output_format == \"json\") {\n JsonUnitTestResultPrinter(\n UnitTestOptions::GetAbsolutePathToOutputFile().c_str())\n .PrintJsonTestList(&stream, test_suites_);\n }\n fprintf(fileout, \"%s\", StringStreamToString(&stream).c_str());\n fclose(fileout);\n }\n}\n\n// Sets the OS stack trace getter.\n//\n// Does nothing if the input and the current OS stack trace getter are\n// the same; otherwise, deletes the old getter and makes the input the\n// current getter.\nvoid UnitTestImpl::set_os_stack_trace_getter(\n OsStackTraceGetterInterface* getter) {\n if (os_stack_trace_getter_ != getter) {\n delete os_stack_trace_getter_;\n os_stack_trace_getter_ = getter;\n }\n}\n\n// Returns the current OS stack trace getter if it is not NULL;\n// otherwise, creates an OsStackTraceGetter, makes it the current\n// getter, and returns it.\nOsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {\n if (os_stack_trace_getter_ == nullptr) {\n#ifdef GTEST_OS_STACK_TRACE_GETTER_\n os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;\n#else\n os_stack_trace_getter_ = new OsStackTraceGetter;\n#endif // GTEST_OS_STACK_TRACE_GETTER_\n }\n\n return os_stack_trace_getter_;\n}\n\n// Returns the most specific TestResult currently running.\nTestResult* UnitTestImpl::current_test_result() {\n if (current_test_info_ != nullptr) {\n return ¤t_test_info_->result_;\n }\n if (current_test_suite_ != nullptr) {\n return ¤t_test_suite_->ad_hoc_test_result_;\n }\n return &ad_hoc_test_result_;\n}\n\n// Shuffles all test suites, and the tests within each test suite,\n// making sure that death tests are still run first.\nvoid UnitTestImpl::ShuffleTests() {\n // Shuffles the death test suites.\n ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_);\n\n // Shuffles the non-death test suites.\n ShuffleRange(random(), last_death_test_suite_ + 1,\n static_cast(test_suites_.size()), &test_suite_indices_);\n\n // Shuffles the tests inside each test suite.\n for (auto& test_suite : test_suites_) {\n test_suite->ShuffleTests(random());\n }\n}\n\n// Restores the test suites and tests to their order before the first shuffle.\nvoid UnitTestImpl::UnshuffleTests() {\n for (size_t i = 0; i < test_suites_.size(); i++) {\n // Unshuffles the tests in each test suite.\n test_suites_[i]->UnshuffleTests();\n // Resets the index of each test suite.\n test_suite_indices_[i] = static_cast(i);\n }\n}\n\n// Returns the current OS stack trace as an std::string.\n//\n// The maximum number of stack frames to be included is specified by\n// the gtest_stack_trace_depth flag. The skip_count parameter\n// specifies the number of top frames to be skipped, which doesn't\n// count against the number of frames to be included.\n//\n// For example, if Foo() calls Bar(), which in turn calls\n// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in\n// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.\nstd::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,\n int skip_count) {\n // We pass skip_count + 1 to skip this wrapper function in addition\n // to what the user really wants to skip.\n return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);\n}\n\n// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to\n// suppress unreachable code warnings.\nnamespace {\nclass ClassUniqueToAlwaysTrue {};\n}\n\nbool IsTrue(bool condition) { return condition; }\n\nbool AlwaysTrue() {\n#if GTEST_HAS_EXCEPTIONS\n // This condition is always false so AlwaysTrue() never actually throws,\n // but it makes the compiler think that it may throw.\n if (IsTrue(false))\n throw ClassUniqueToAlwaysTrue();\n#endif // GTEST_HAS_EXCEPTIONS\n return true;\n}\n\n// If *pstr starts with the given prefix, modifies *pstr to be right\n// past the prefix and returns true; otherwise leaves *pstr unchanged\n// and returns false. None of pstr, *pstr, and prefix can be NULL.\nbool SkipPrefix(const char* prefix, const char** pstr) {\n const size_t prefix_len = strlen(prefix);\n if (strncmp(*pstr, prefix, prefix_len) == 0) {\n *pstr += prefix_len;\n return true;\n }\n return false;\n}\n\n// Parses a string as a command line flag. The string should have\n// the format \"--flag=value\". When def_optional is true, the \"=value\"\n// part can be omitted.\n//\n// Returns the value of the flag, or NULL if the parsing failed.\nstatic const char* ParseFlagValue(const char* str, const char* flag,\n bool def_optional) {\n // str and flag must not be NULL.\n if (str == nullptr || flag == nullptr) return nullptr;\n\n // The flag must start with \"--\" followed by GTEST_FLAG_PREFIX_.\n const std::string flag_str = std::string(\"--\") + GTEST_FLAG_PREFIX_ + flag;\n const size_t flag_len = flag_str.length();\n if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;\n\n // Skips the flag name.\n const char* flag_end = str + flag_len;\n\n // When def_optional is true, it's OK to not have a \"=value\" part.\n if (def_optional && (flag_end[0] == '\\0')) {\n return flag_end;\n }\n\n // If def_optional is true and there are more characters after the\n // flag name, or if def_optional is false, there must be a '=' after\n // the flag name.\n if (flag_end[0] != '=') return nullptr;\n\n // Returns the string after \"=\".\n return flag_end + 1;\n}\n\n// Parses a string for a bool flag, in the form of either\n// \"--flag=value\" or \"--flag\".\n//\n// In the former case, the value is taken as true as long as it does\n// not start with '0', 'f', or 'F'.\n//\n// In the latter case, the value is taken as true.\n//\n// On success, stores the value of the flag in *value, and returns\n// true. On failure, returns false without changing *value.\nstatic bool ParseBoolFlag(const char* str, const char* flag, bool* value) {\n // Gets the value of the flag as a string.\n const char* const value_str = ParseFlagValue(str, flag, true);\n\n // Aborts if the parsing failed.\n if (value_str == nullptr) return false;\n\n // Converts the string value to a bool.\n *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');\n return true;\n}\n\n// Parses a string for an int32_t flag, in the form of \"--flag=value\".\n//\n// On success, stores the value of the flag in *value, and returns\n// true. On failure, returns false without changing *value.\nbool ParseInt32Flag(const char* str, const char* flag, int32_t* value) {\n // Gets the value of the flag as a string.\n const char* const value_str = ParseFlagValue(str, flag, false);\n\n // Aborts if the parsing failed.\n if (value_str == nullptr) return false;\n\n // Sets *value to the value of the flag.\n return ParseInt32(Message() << \"The value of flag --\" << flag,\n value_str, value);\n}\n\n// Parses a string for a string flag, in the form of \"--flag=value\".\n//\n// On success, stores the value of the flag in *value, and returns\n// true. On failure, returns false without changing *value.\ntemplate \nstatic bool ParseStringFlag(const char* str, const char* flag, String* value) {\n // Gets the value of the flag as a string.\n const char* const value_str = ParseFlagValue(str, flag, false);\n\n // Aborts if the parsing failed.\n if (value_str == nullptr) return false;\n\n // Sets *value to the value of the flag.\n *value = value_str;\n return true;\n}\n\n// Determines whether a string has a prefix that Google Test uses for its\n// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.\n// If Google Test detects that a command line flag has its prefix but is not\n// recognized, it will print its help message. Flags starting with\n// GTEST_INTERNAL_PREFIX_ followed by \"internal_\" are considered Google Test\n// internal flags and do not trigger the help message.\nstatic bool HasGoogleTestFlagPrefix(const char* str) {\n return (SkipPrefix(\"--\", &str) ||\n SkipPrefix(\"-\", &str) ||\n SkipPrefix(\"/\", &str)) &&\n !SkipPrefix(GTEST_FLAG_PREFIX_ \"internal_\", &str) &&\n (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||\n SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));\n}\n\n// Prints a string containing code-encoded text. The following escape\n// sequences can be used in the string to control the text color:\n//\n// @@ prints a single '@' character.\n// @R changes the color to red.\n// @G changes the color to green.\n// @Y changes the color to yellow.\n// @D changes to the default terminal text color.\n//\nstatic void PrintColorEncoded(const char* str) {\n GTestColor color = GTestColor::kDefault; // The current color.\n\n // Conceptually, we split the string into segments divided by escape\n // sequences. Then we print one segment at a time. At the end of\n // each iteration, the str pointer advances to the beginning of the\n // next segment.\n for (;;) {\n const char* p = strchr(str, '@');\n if (p == nullptr) {\n ColoredPrintf(color, \"%s\", str);\n return;\n }\n\n ColoredPrintf(color, \"%s\", std::string(str, p).c_str());\n\n const char ch = p[1];\n str = p + 2;\n if (ch == '@') {\n ColoredPrintf(color, \"@\");\n } else if (ch == 'D') {\n color = GTestColor::kDefault;\n } else if (ch == 'R') {\n color = GTestColor::kRed;\n } else if (ch == 'G') {\n color = GTestColor::kGreen;\n } else if (ch == 'Y') {\n color = GTestColor::kYellow;\n } else {\n --str;\n }\n }\n}\n\nstatic const char kColorEncodedHelpMessage[] =\n \"This program contains tests written using \" GTEST_NAME_\n \". You can use the\\n\"\n \"following command line flags to control its behavior:\\n\"\n \"\\n\"\n \"Test Selection:\\n\"\n \" @G--\" GTEST_FLAG_PREFIX_\n \"list_tests@D\\n\"\n \" List the names of all tests instead of running them. The name of\\n\"\n \" TEST(Foo, Bar) is \\\"Foo.Bar\\\".\\n\"\n \" @G--\" GTEST_FLAG_PREFIX_\n \"filter=@YPOSITIVE_PATTERNS\"\n \"[@G-@YNEGATIVE_PATTERNS]@D\\n\"\n \" Run only the tests whose name matches one of the positive patterns \"\n \"but\\n\"\n \" none of the negative patterns. '?' matches any single character; \"\n \"'*'\\n\"\n \" matches any substring; ':' separates two patterns.\\n\"\n \" @G--\" GTEST_FLAG_PREFIX_\n \"also_run_disabled_tests@D\\n\"\n \" Run all disabled tests too.\\n\"\n \"\\n\"\n \"Test Execution:\\n\"\n \" @G--\" GTEST_FLAG_PREFIX_\n \"repeat=@Y[COUNT]@D\\n\"\n \" Run the tests repeatedly; use a negative count to repeat forever.\\n\"\n \" @G--\" GTEST_FLAG_PREFIX_\n \"shuffle@D\\n\"\n \" Randomize tests' orders on every iteration.\\n\"\n \" @G--\" GTEST_FLAG_PREFIX_\n \"random_seed=@Y[NUMBER]@D\\n\"\n \" Random number seed to use for shuffling test orders (between 1 and\\n\"\n \" 99999, or 0 to use a seed based on the current time).\\n\"\n \"\\n\"\n \"Test Output:\\n\"\n \" @G--\" GTEST_FLAG_PREFIX_\n \"color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\\n\"\n \" Enable/disable colored output. The default is @Gauto@D.\\n\"\n \" @G--\" GTEST_FLAG_PREFIX_\n \"brief=1@D\\n\"\n \" Only print test failures.\\n\"\n \" @G--\" GTEST_FLAG_PREFIX_\n \"print_time=0@D\\n\"\n \" Don't print the elapsed time of each test.\\n\"\n \" @G--\" GTEST_FLAG_PREFIX_\n \"output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G\" GTEST_PATH_SEP_\n \"@Y|@G:@YFILE_PATH]@D\\n\"\n \" Generate a JSON or XML report in the given directory or with the \"\n \"given\\n\"\n \" file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\\n\"\n# if GTEST_CAN_STREAM_RESULTS_\n \" @G--\" GTEST_FLAG_PREFIX_\n \"stream_result_to=@YHOST@G:@YPORT@D\\n\"\n \" Stream test results to the given server.\\n\"\n# endif // GTEST_CAN_STREAM_RESULTS_\n \"\\n\"\n \"Assertion Behavior:\\n\"\n# if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS\n \" @G--\" GTEST_FLAG_PREFIX_\n \"death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\\n\"\n \" Set the default death test style.\\n\"\n# endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS\n \" @G--\" GTEST_FLAG_PREFIX_\n \"break_on_failure@D\\n\"\n \" Turn assertion failures into debugger break-points.\\n\"\n \" @G--\" GTEST_FLAG_PREFIX_\n \"throw_on_failure@D\\n\"\n \" Turn assertion failures into C++ exceptions for use by an external\\n\"\n \" test framework.\\n\"\n \" @G--\" GTEST_FLAG_PREFIX_\n \"catch_exceptions=0@D\\n\"\n \" Do not report exceptions as test failures. Instead, allow them\\n\"\n \" to crash the program or throw a pop-up (on Windows).\\n\"\n \"\\n\"\n \"Except for @G--\" GTEST_FLAG_PREFIX_\n \"list_tests@D, you can alternatively set \"\n \"the corresponding\\n\"\n \"environment variable of a flag (all letters in upper-case). For example, \"\n \"to\\n\"\n \"disable colored text output, you can either specify \"\n \"@G--\" GTEST_FLAG_PREFIX_\n \"color=no@D or set\\n\"\n \"the @G\" GTEST_FLAG_PREFIX_UPPER_\n \"COLOR@D environment variable to @Gno@D.\\n\"\n \"\\n\"\n \"For more information, please read the \" GTEST_NAME_\n \" documentation at\\n\"\n \"@G\" GTEST_PROJECT_URL_ \"@D. If you find a bug in \" GTEST_NAME_\n \"\\n\"\n \"(not one in your own code or tests), please report it to\\n\"\n \"@G<\" GTEST_DEV_EMAIL_ \">@D.\\n\";\n\nstatic bool ParseGoogleTestFlag(const char* const arg) {\n return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,\n >EST_FLAG(also_run_disabled_tests)) ||\n ParseBoolFlag(arg, kBreakOnFailureFlag,\n >EST_FLAG(break_on_failure)) ||\n ParseBoolFlag(arg, kCatchExceptionsFlag,\n >EST_FLAG(catch_exceptions)) ||\n ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) ||\n ParseStringFlag(arg, kDeathTestStyleFlag,\n >EST_FLAG(death_test_style)) ||\n ParseBoolFlag(arg, kDeathTestUseFork,\n >EST_FLAG(death_test_use_fork)) ||\n ParseBoolFlag(arg, kFailFast, >EST_FLAG(fail_fast)) ||\n ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) ||\n ParseStringFlag(arg, kInternalRunDeathTestFlag,\n >EST_FLAG(internal_run_death_test)) ||\n ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) ||\n ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) ||\n ParseBoolFlag(arg, kBriefFlag, >EST_FLAG(brief)) ||\n ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) ||\n ParseBoolFlag(arg, kPrintUTF8Flag, >EST_FLAG(print_utf8)) ||\n ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) ||\n ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) ||\n ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) ||\n ParseInt32Flag(arg, kStackTraceDepthFlag,\n >EST_FLAG(stack_trace_depth)) ||\n ParseStringFlag(arg, kStreamResultToFlag,\n >EST_FLAG(stream_result_to)) ||\n ParseBoolFlag(arg, kThrowOnFailureFlag, >EST_FLAG(throw_on_failure));\n}\n\n#if GTEST_USE_OWN_FLAGFILE_FLAG_\nstatic void LoadFlagsFromFile(const std::string& path) {\n FILE* flagfile = posix::FOpen(path.c_str(), \"r\");\n if (!flagfile) {\n GTEST_LOG_(FATAL) << \"Unable to open file \\\"\" << GTEST_FLAG(flagfile)\n << \"\\\"\";\n }\n std::string contents(ReadEntireFile(flagfile));\n posix::FClose(flagfile);\n std::vector lines;\n SplitString(contents, '\\n', &lines);\n for (size_t i = 0; i < lines.size(); ++i) {\n if (lines[i].empty())\n continue;\n if (!ParseGoogleTestFlag(lines[i].c_str()))\n g_help_flag = true;\n }\n}\n#endif // GTEST_USE_OWN_FLAGFILE_FLAG_\n\n// Parses the command line for Google Test flags, without initializing\n// other parts of Google Test. The type parameter CharType can be\n// instantiated to either char or wchar_t.\ntemplate \nvoid ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {\n for (int i = 1; i < *argc; i++) {\n const std::string arg_string = StreamableToString(argv[i]);\n const char* const arg = arg_string.c_str();\n\n using internal::ParseBoolFlag;\n using internal::ParseInt32Flag;\n using internal::ParseStringFlag;\n\n bool remove_flag = false;\n if (ParseGoogleTestFlag(arg)) {\n remove_flag = true;\n#if GTEST_USE_OWN_FLAGFILE_FLAG_\n } else if (ParseStringFlag(arg, kFlagfileFlag, >EST_FLAG(flagfile))) {\n LoadFlagsFromFile(GTEST_FLAG(flagfile));\n remove_flag = true;\n#endif // GTEST_USE_OWN_FLAGFILE_FLAG_\n } else if (arg_string == \"--help\" || arg_string == \"-h\" ||\n arg_string == \"-?\" || arg_string == \"/?\" ||\n HasGoogleTestFlagPrefix(arg)) {\n // Both help flag and unrecognized Google Test flags (excluding\n // internal ones) trigger help display.\n g_help_flag = true;\n }\n\n if (remove_flag) {\n // Shift the remainder of the argv list left by one. Note\n // that argv has (*argc + 1) elements, the last one always being\n // NULL. The following loop moves the trailing NULL element as\n // well.\n for (int j = i; j != *argc; j++) {\n argv[j] = argv[j + 1];\n }\n\n // Decrements the argument count.\n (*argc)--;\n\n // We also need to decrement the iterator as we just removed\n // an element.\n i--;\n }\n }\n\n if (g_help_flag) {\n // We print the help here instead of in RUN_ALL_TESTS(), as the\n // latter may not be called at all if the user is using Google\n // Test with another testing framework.\n PrintColorEncoded(kColorEncodedHelpMessage);\n }\n}\n\n// Parses the command line for Google Test flags, without initializing\n// other parts of Google Test.\nvoid ParseGoogleTestFlagsOnly(int* argc, char** argv) {\n ParseGoogleTestFlagsOnlyImpl(argc, argv);\n\n // Fix the value of *_NSGetArgc() on macOS, but if and only if\n // *_NSGetArgv() == argv\n // Only applicable to char** version of argv\n#if GTEST_OS_MAC\n#ifndef GTEST_OS_IOS\n if (*_NSGetArgv() == argv) {\n *_NSGetArgc() = *argc;\n }\n#endif\n#endif\n}\nvoid ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {\n ParseGoogleTestFlagsOnlyImpl(argc, argv);\n}\n\n// The internal implementation of InitGoogleTest().\n//\n// The type parameter CharType can be instantiated to either char or\n// wchar_t.\ntemplate \nvoid InitGoogleTestImpl(int* argc, CharType** argv) {\n // We don't want to run the initialization code twice.\n if (GTestIsInitialized()) return;\n\n if (*argc <= 0) return;\n\n g_argvs.clear();\n for (int i = 0; i != *argc; i++) {\n g_argvs.push_back(StreamableToString(argv[i]));\n }\n\n#if GTEST_HAS_ABSL\n absl::InitializeSymbolizer(g_argvs[0].c_str());\n#endif // GTEST_HAS_ABSL\n\n ParseGoogleTestFlagsOnly(argc, argv);\n GetUnitTestImpl()->PostFlagParsingInit();\n}\n\n} // namespace internal\n\n// Initializes Google Test. This must be called before calling\n// RUN_ALL_TESTS(). In particular, it parses a command line for the\n// flags that Google Test recognizes. Whenever a Google Test flag is\n// seen, it is removed from argv, and *argc is decremented.\n//\n// No value is returned. Instead, the Google Test flag variables are\n// updated.\n//\n// Calling the function for the second time has no user-visible effect.\nvoid InitGoogleTest(int* argc, char** argv) {\n#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);\n#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n internal::InitGoogleTestImpl(argc, argv);\n#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n}\n\n// This overloaded version can be used in Windows programs compiled in\n// UNICODE mode.\nvoid InitGoogleTest(int* argc, wchar_t** argv) {\n#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);\n#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n internal::InitGoogleTestImpl(argc, argv);\n#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n}\n\n// This overloaded version can be used on Arduino/embedded platforms where\n// there is no argc/argv.\nvoid InitGoogleTest() {\n // Since Arduino doesn't have a command line, fake out the argc/argv arguments\n int argc = 1;\n const auto arg0 = \"dummy\";\n char* argv0 = const_cast(arg0);\n char** argv = &argv0;\n\n#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv);\n#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n internal::InitGoogleTestImpl(&argc, argv);\n#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n}\n\nstd::string TempDir() {\n#if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)\n return GTEST_CUSTOM_TEMPDIR_FUNCTION_();\n#elif GTEST_OS_WINDOWS_MOBILE\n return \"\\\\temp\\\\\";\n#elif GTEST_OS_WINDOWS\n const char* temp_dir = internal::posix::GetEnv(\"TEMP\");\n if (temp_dir == nullptr || temp_dir[0] == '\\0') {\n return \"\\\\temp\\\\\";\n } else if (temp_dir[strlen(temp_dir) - 1] == '\\\\') {\n return temp_dir;\n } else {\n return std::string(temp_dir) + \"\\\\\";\n }\n#elif GTEST_OS_LINUX_ANDROID\n const char* temp_dir = internal::posix::GetEnv(\"TEST_TMPDIR\");\n if (temp_dir == nullptr || temp_dir[0] == '\\0') {\n return \"/data/local/tmp/\";\n } else {\n return temp_dir;\n }\n#elif GTEST_OS_LINUX\n const char* temp_dir = internal::posix::GetEnv(\"TEST_TMPDIR\");\n if (temp_dir == nullptr || temp_dir[0] == '\\0') {\n return \"/tmp/\";\n } else {\n return temp_dir;\n }\n#else\n return \"/tmp/\";\n#endif // GTEST_OS_WINDOWS_MOBILE\n}\n\n// Class ScopedTrace\n\n// Pushes the given source file location and message onto a per-thread\n// trace stack maintained by Google Test.\nvoid ScopedTrace::PushTrace(const char* file, int line, std::string message) {\n internal::TraceInfo trace;\n trace.file = file;\n trace.line = line;\n trace.message.swap(message);\n\n UnitTest::GetInstance()->PushGTestTrace(trace);\n}\n\n// Pops the info pushed by the c'tor.\nScopedTrace::~ScopedTrace()\n GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {\n UnitTest::GetInstance()->PopGTestTrace();\n}\n\n} // namespace testing\n// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// This file implements death tests.\n\n\n#include \n#include \n\n\n#if GTEST_HAS_DEATH_TEST\n\n# if GTEST_OS_MAC\n# include \n# endif // GTEST_OS_MAC\n\n# include \n# include \n# include \n\n# if GTEST_OS_LINUX\n# include \n# endif // GTEST_OS_LINUX\n\n# include \n\n# if GTEST_OS_WINDOWS\n# include \n# else\n# include \n# include \n# endif // GTEST_OS_WINDOWS\n\n# if GTEST_OS_QNX\n# include \n# endif // GTEST_OS_QNX\n\n# if GTEST_OS_FUCHSIA\n# include \n# include \n# include \n# include \n# include \n# include \n# include \n# include \n# include \n# include \n# include \n# endif // GTEST_OS_FUCHSIA\n\n#endif // GTEST_HAS_DEATH_TEST\n\n\nnamespace testing {\n\n// Constants.\n\n// The default death test style.\n//\n// This is defined in internal/gtest-port.h as \"fast\", but can be overridden by\n// a definition in internal/custom/gtest-port.h. The recommended value, which is\n// used internally at Google, is \"threadsafe\".\nstatic const char kDefaultDeathTestStyle[] = GTEST_DEFAULT_DEATH_TEST_STYLE;\n\nGTEST_DEFINE_string_(\n death_test_style,\n internal::StringFromGTestEnv(\"death_test_style\", kDefaultDeathTestStyle),\n \"Indicates how to run a death test in a forked child process: \"\n \"\\\"threadsafe\\\" (child process re-executes the test binary \"\n \"from the beginning, running only the specific death test) or \"\n \"\\\"fast\\\" (child process runs the death test immediately \"\n \"after forking).\");\n\nGTEST_DEFINE_bool_(\n death_test_use_fork,\n internal::BoolFromGTestEnv(\"death_test_use_fork\", false),\n \"Instructs to use fork()/_exit() instead of clone() in death tests. \"\n \"Ignored and always uses fork() on POSIX systems where clone() is not \"\n \"implemented. Useful when running under valgrind or similar tools if \"\n \"those do not support clone(). Valgrind 3.3.1 will just fail if \"\n \"it sees an unsupported combination of clone() flags. \"\n \"It is not recommended to use this flag w/o valgrind though it will \"\n \"work in 99% of the cases. Once valgrind is fixed, this flag will \"\n \"most likely be removed.\");\n\nnamespace internal {\nGTEST_DEFINE_string_(\n internal_run_death_test, \"\",\n \"Indicates the file, line number, temporal index of \"\n \"the single death test to run, and a file descriptor to \"\n \"which a success code may be sent, all separated by \"\n \"the '|' characters. This flag is specified if and only if the \"\n \"current process is a sub-process launched for running a thread-safe \"\n \"death test. FOR INTERNAL USE ONLY.\");\n} // namespace internal\n\n#if GTEST_HAS_DEATH_TEST\n\nnamespace internal {\n\n// Valid only for fast death tests. Indicates the code is running in the\n// child process of a fast style death test.\n# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA\nstatic bool g_in_fast_death_test_child = false;\n# endif\n\n// Returns a Boolean value indicating whether the caller is currently\n// executing in the context of the death test child process. Tools such as\n// Valgrind heap checkers may need this to modify their behavior in death\n// tests. IMPORTANT: This is an internal utility. Using it may break the\n// implementation of death tests. User code MUST NOT use it.\nbool InDeathTestChild() {\n# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA\n\n // On Windows and Fuchsia, death tests are thread-safe regardless of the value\n // of the death_test_style flag.\n return !GTEST_FLAG(internal_run_death_test).empty();\n\n# else\n\n if (GTEST_FLAG(death_test_style) == \"threadsafe\")\n return !GTEST_FLAG(internal_run_death_test).empty();\n else\n return g_in_fast_death_test_child;\n#endif\n}\n\n} // namespace internal\n\n// ExitedWithCode constructor.\nExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {\n}\n\n// ExitedWithCode function-call operator.\nbool ExitedWithCode::operator()(int exit_status) const {\n# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA\n\n return exit_status == exit_code_;\n\n# else\n\n return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;\n\n# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA\n}\n\n# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA\n// KilledBySignal constructor.\nKilledBySignal::KilledBySignal(int signum) : signum_(signum) {\n}\n\n// KilledBySignal function-call operator.\nbool KilledBySignal::operator()(int exit_status) const {\n# if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)\n {\n bool result;\n if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {\n return result;\n }\n }\n# endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)\n return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;\n}\n# endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA\n\nnamespace internal {\n\n// Utilities needed for death tests.\n\n// Generates a textual description of a given exit code, in the format\n// specified by wait(2).\nstatic std::string ExitSummary(int exit_code) {\n Message m;\n\n# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA\n\n m << \"Exited with exit status \" << exit_code;\n\n# else\n\n if (WIFEXITED(exit_code)) {\n m << \"Exited with exit status \" << WEXITSTATUS(exit_code);\n } else if (WIFSIGNALED(exit_code)) {\n m << \"Terminated by signal \" << WTERMSIG(exit_code);\n }\n# ifdef WCOREDUMP\n if (WCOREDUMP(exit_code)) {\n m << \" (core dumped)\";\n }\n# endif\n# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA\n\n return m.GetString();\n}\n\n// Returns true if exit_status describes a process that was terminated\n// by a signal, or exited normally with a nonzero exit code.\nbool ExitedUnsuccessfully(int exit_status) {\n return !ExitedWithCode(0)(exit_status);\n}\n\n# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA\n// Generates a textual failure message when a death test finds more than\n// one thread running, or cannot determine the number of threads, prior\n// to executing the given statement. It is the responsibility of the\n// caller not to pass a thread_count of 1.\nstatic std::string DeathTestThreadWarning(size_t thread_count) {\n Message msg;\n msg << \"Death tests use fork(), which is unsafe particularly\"\n << \" in a threaded context. For this test, \" << GTEST_NAME_ << \" \";\n if (thread_count == 0) {\n msg << \"couldn't detect the number of threads.\";\n } else {\n msg << \"detected \" << thread_count << \" threads.\";\n }\n msg << \" See \"\n \"https://github.com/google/googletest/blob/master/docs/\"\n \"advanced.md#death-tests-and-threads\"\n << \" for more explanation and suggested solutions, especially if\"\n << \" this is the last message you see before your test times out.\";\n return msg.GetString();\n}\n# endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA\n\n// Flag characters for reporting a death test that did not die.\nstatic const char kDeathTestLived = 'L';\nstatic const char kDeathTestReturned = 'R';\nstatic const char kDeathTestThrew = 'T';\nstatic const char kDeathTestInternalError = 'I';\n\n#if GTEST_OS_FUCHSIA\n\n// File descriptor used for the pipe in the child process.\nstatic const int kFuchsiaReadPipeFd = 3;\n\n#endif\n\n// An enumeration describing all of the possible ways that a death test can\n// conclude. DIED means that the process died while executing the test\n// code; LIVED means that process lived beyond the end of the test code;\n// RETURNED means that the test statement attempted to execute a return\n// statement, which is not allowed; THREW means that the test statement\n// returned control by throwing an exception. IN_PROGRESS means the test\n// has not yet concluded.\nenum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };\n\n// Routine for aborting the program which is safe to call from an\n// exec-style death test child process, in which case the error\n// message is propagated back to the parent process. Otherwise, the\n// message is simply printed to stderr. In either case, the program\n// then exits with status 1.\nstatic void DeathTestAbort(const std::string& message) {\n // On a POSIX system, this function may be called from a threadsafe-style\n // death test child process, which operates on a very small stack. Use\n // the heap for any additional non-minuscule memory requirements.\n const InternalRunDeathTestFlag* const flag =\n GetUnitTestImpl()->internal_run_death_test_flag();\n if (flag != nullptr) {\n FILE* parent = posix::FDOpen(flag->write_fd(), \"w\");\n fputc(kDeathTestInternalError, parent);\n fprintf(parent, \"%s\", message.c_str());\n fflush(parent);\n _exit(1);\n } else {\n fprintf(stderr, \"%s\", message.c_str());\n fflush(stderr);\n posix::Abort();\n }\n}\n\n// A replacement for CHECK that calls DeathTestAbort if the assertion\n// fails.\n# define GTEST_DEATH_TEST_CHECK_(expression) \\\n do { \\\n if (!::testing::internal::IsTrue(expression)) { \\\n DeathTestAbort( \\\n ::std::string(\"CHECK failed: File \") + __FILE__ + \", line \" \\\n + ::testing::internal::StreamableToString(__LINE__) + \": \" \\\n + #expression); \\\n } \\\n } while (::testing::internal::AlwaysFalse())\n\n// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for\n// evaluating any system call that fulfills two conditions: it must return\n// -1 on failure, and set errno to EINTR when it is interrupted and\n// should be tried again. The macro expands to a loop that repeatedly\n// evaluates the expression as long as it evaluates to -1 and sets\n// errno to EINTR. If the expression evaluates to -1 but errno is\n// something other than EINTR, DeathTestAbort is called.\n# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \\\n do { \\\n int gtest_retval; \\\n do { \\\n gtest_retval = (expression); \\\n } while (gtest_retval == -1 && errno == EINTR); \\\n if (gtest_retval == -1) { \\\n DeathTestAbort( \\\n ::std::string(\"CHECK failed: File \") + __FILE__ + \", line \" \\\n + ::testing::internal::StreamableToString(__LINE__) + \": \" \\\n + #expression + \" != -1\"); \\\n } \\\n } while (::testing::internal::AlwaysFalse())\n\n// Returns the message describing the last system error in errno.\nstd::string GetLastErrnoDescription() {\n return errno == 0 ? \"\" : posix::StrError(errno);\n}\n\n// This is called from a death test parent process to read a failure\n// message from the death test child process and log it with the FATAL\n// severity. On Windows, the message is read from a pipe handle. On other\n// platforms, it is read from a file descriptor.\nstatic void FailFromInternalError(int fd) {\n Message error;\n char buffer[256];\n int num_read;\n\n do {\n while ((num_read = posix::Read(fd, buffer, 255)) > 0) {\n buffer[num_read] = '\\0';\n error << buffer;\n }\n } while (num_read == -1 && errno == EINTR);\n\n if (num_read == 0) {\n GTEST_LOG_(FATAL) << error.GetString();\n } else {\n const int last_error = errno;\n GTEST_LOG_(FATAL) << \"Error while reading death test internal: \"\n << GetLastErrnoDescription() << \" [\" << last_error << \"]\";\n }\n}\n\n// Death test constructor. Increments the running death test count\n// for the current test.\nDeathTest::DeathTest() {\n TestInfo* const info = GetUnitTestImpl()->current_test_info();\n if (info == nullptr) {\n DeathTestAbort(\"Cannot run a death test outside of a TEST or \"\n \"TEST_F construct\");\n }\n}\n\n// Creates and returns a death test by dispatching to the current\n// death test factory.\nbool DeathTest::Create(const char* statement,\n Matcher matcher, const char* file,\n int line, DeathTest** test) {\n return GetUnitTestImpl()->death_test_factory()->Create(\n statement, std::move(matcher), file, line, test);\n}\n\nconst char* DeathTest::LastMessage() {\n return last_death_test_message_.c_str();\n}\n\nvoid DeathTest::set_last_death_test_message(const std::string& message) {\n last_death_test_message_ = message;\n}\n\nstd::string DeathTest::last_death_test_message_;\n\n// Provides cross platform implementation for some death functionality.\nclass DeathTestImpl : public DeathTest {\n protected:\n DeathTestImpl(const char* a_statement, Matcher matcher)\n : statement_(a_statement),\n matcher_(std::move(matcher)),\n spawned_(false),\n status_(-1),\n outcome_(IN_PROGRESS),\n read_fd_(-1),\n write_fd_(-1) {}\n\n // read_fd_ is expected to be closed and cleared by a derived class.\n ~DeathTestImpl() override { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }\n\n void Abort(AbortReason reason) override;\n bool Passed(bool status_ok) override;\n\n const char* statement() const { return statement_; }\n bool spawned() const { return spawned_; }\n void set_spawned(bool is_spawned) { spawned_ = is_spawned; }\n int status() const { return status_; }\n void set_status(int a_status) { status_ = a_status; }\n DeathTestOutcome outcome() const { return outcome_; }\n void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }\n int read_fd() const { return read_fd_; }\n void set_read_fd(int fd) { read_fd_ = fd; }\n int write_fd() const { return write_fd_; }\n void set_write_fd(int fd) { write_fd_ = fd; }\n\n // Called in the parent process only. Reads the result code of the death\n // test child process via a pipe, interprets it to set the outcome_\n // member, and closes read_fd_. Outputs diagnostics and terminates in\n // case of unexpected codes.\n void ReadAndInterpretStatusByte();\n\n // Returns stderr output from the child process.\n virtual std::string GetErrorLogs();\n\n private:\n // The textual content of the code this object is testing. This class\n // doesn't own this string and should not attempt to delete it.\n const char* const statement_;\n // A matcher that's expected to match the stderr output by the child process.\n Matcher matcher_;\n // True if the death test child process has been successfully spawned.\n bool spawned_;\n // The exit status of the child process.\n int status_;\n // How the death test concluded.\n DeathTestOutcome outcome_;\n // Descriptor to the read end of the pipe to the child process. It is\n // always -1 in the child process. The child keeps its write end of the\n // pipe in write_fd_.\n int read_fd_;\n // Descriptor to the child's write end of the pipe to the parent process.\n // It is always -1 in the parent process. The parent keeps its end of the\n // pipe in read_fd_.\n int write_fd_;\n};\n\n// Called in the parent process only. Reads the result code of the death\n// test child process via a pipe, interprets it to set the outcome_\n// member, and closes read_fd_. Outputs diagnostics and terminates in\n// case of unexpected codes.\nvoid DeathTestImpl::ReadAndInterpretStatusByte() {\n char flag;\n int bytes_read;\n\n // The read() here blocks until data is available (signifying the\n // failure of the death test) or until the pipe is closed (signifying\n // its success), so it's okay to call this in the parent before\n // the child process has exited.\n do {\n bytes_read = posix::Read(read_fd(), &flag, 1);\n } while (bytes_read == -1 && errno == EINTR);\n\n if (bytes_read == 0) {\n set_outcome(DIED);\n } else if (bytes_read == 1) {\n switch (flag) {\n case kDeathTestReturned:\n set_outcome(RETURNED);\n break;\n case kDeathTestThrew:\n set_outcome(THREW);\n break;\n case kDeathTestLived:\n set_outcome(LIVED);\n break;\n case kDeathTestInternalError:\n FailFromInternalError(read_fd()); // Does not return.\n break;\n default:\n GTEST_LOG_(FATAL) << \"Death test child process reported \"\n << \"unexpected status byte (\"\n << static_cast(flag) << \")\";\n }\n } else {\n GTEST_LOG_(FATAL) << \"Read from death test child process failed: \"\n << GetLastErrnoDescription();\n }\n GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));\n set_read_fd(-1);\n}\n\nstd::string DeathTestImpl::GetErrorLogs() {\n return GetCapturedStderr();\n}\n\n// Signals that the death test code which should have exited, didn't.\n// Should be called only in a death test child process.\n// Writes a status byte to the child's status file descriptor, then\n// calls _exit(1).\nvoid DeathTestImpl::Abort(AbortReason reason) {\n // The parent process considers the death test to be a failure if\n // it finds any data in our pipe. So, here we write a single flag byte\n // to the pipe, then exit.\n const char status_ch =\n reason == TEST_DID_NOT_DIE ? kDeathTestLived :\n reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;\n\n GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));\n // We are leaking the descriptor here because on some platforms (i.e.,\n // when built as Windows DLL), destructors of global objects will still\n // run after calling _exit(). On such systems, write_fd_ will be\n // indirectly closed from the destructor of UnitTestImpl, causing double\n // close if it is also closed here. On debug configurations, double close\n // may assert. As there are no in-process buffers to flush here, we are\n // relying on the OS to close the descriptor after the process terminates\n // when the destructors are not run.\n _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)\n}\n\n// Returns an indented copy of stderr output for a death test.\n// This makes distinguishing death test output lines from regular log lines\n// much easier.\nstatic ::std::string FormatDeathTestOutput(const ::std::string& output) {\n ::std::string ret;\n for (size_t at = 0; ; ) {\n const size_t line_end = output.find('\\n', at);\n ret += \"[ DEATH ] \";\n if (line_end == ::std::string::npos) {\n ret += output.substr(at);\n break;\n }\n ret += output.substr(at, line_end + 1 - at);\n at = line_end + 1;\n }\n return ret;\n}\n\n// Assesses the success or failure of a death test, using both private\n// members which have previously been set, and one argument:\n//\n// Private data members:\n// outcome: An enumeration describing how the death test\n// concluded: DIED, LIVED, THREW, or RETURNED. The death test\n// fails in the latter three cases.\n// status: The exit status of the child process. On *nix, it is in the\n// in the format specified by wait(2). On Windows, this is the\n// value supplied to the ExitProcess() API or a numeric code\n// of the exception that terminated the program.\n// matcher_: A matcher that's expected to match the stderr output by the child\n// process.\n//\n// Argument:\n// status_ok: true if exit_status is acceptable in the context of\n// this particular death test, which fails if it is false\n//\n// Returns true if and only if all of the above conditions are met. Otherwise,\n// the first failing condition, in the order given above, is the one that is\n// reported. Also sets the last death test message string.\nbool DeathTestImpl::Passed(bool status_ok) {\n if (!spawned())\n return false;\n\n const std::string error_message = GetErrorLogs();\n\n bool success = false;\n Message buffer;\n\n buffer << \"Death test: \" << statement() << \"\\n\";\n switch (outcome()) {\n case LIVED:\n buffer << \" Result: failed to die.\\n\"\n << \" Error msg:\\n\" << FormatDeathTestOutput(error_message);\n break;\n case THREW:\n buffer << \" Result: threw an exception.\\n\"\n << \" Error msg:\\n\" << FormatDeathTestOutput(error_message);\n break;\n case RETURNED:\n buffer << \" Result: illegal return in test statement.\\n\"\n << \" Error msg:\\n\" << FormatDeathTestOutput(error_message);\n break;\n case DIED:\n if (status_ok) {\n if (matcher_.Matches(error_message)) {\n success = true;\n } else {\n std::ostringstream stream;\n matcher_.DescribeTo(&stream);\n buffer << \" Result: died but not with expected error.\\n\"\n << \" Expected: \" << stream.str() << \"\\n\"\n << \"Actual msg:\\n\"\n << FormatDeathTestOutput(error_message);\n }\n } else {\n buffer << \" Result: died but not with expected exit code:\\n\"\n << \" \" << ExitSummary(status()) << \"\\n\"\n << \"Actual msg:\\n\" << FormatDeathTestOutput(error_message);\n }\n break;\n case IN_PROGRESS:\n default:\n GTEST_LOG_(FATAL)\n << \"DeathTest::Passed somehow called before conclusion of test\";\n }\n\n DeathTest::set_last_death_test_message(buffer.GetString());\n return success;\n}\n\n# if GTEST_OS_WINDOWS\n// WindowsDeathTest implements death tests on Windows. Due to the\n// specifics of starting new processes on Windows, death tests there are\n// always threadsafe, and Google Test considers the\n// --gtest_death_test_style=fast setting to be equivalent to\n// --gtest_death_test_style=threadsafe there.\n//\n// A few implementation notes: Like the Linux version, the Windows\n// implementation uses pipes for child-to-parent communication. But due to\n// the specifics of pipes on Windows, some extra steps are required:\n//\n// 1. The parent creates a communication pipe and stores handles to both\n// ends of it.\n// 2. The parent starts the child and provides it with the information\n// necessary to acquire the handle to the write end of the pipe.\n// 3. The child acquires the write end of the pipe and signals the parent\n// using a Windows event.\n// 4. Now the parent can release the write end of the pipe on its side. If\n// this is done before step 3, the object's reference count goes down to\n// 0 and it is destroyed, preventing the child from acquiring it. The\n// parent now has to release it, or read operations on the read end of\n// the pipe will not return when the child terminates.\n// 5. The parent reads child's output through the pipe (outcome code and\n// any possible error messages) from the pipe, and its stderr and then\n// determines whether to fail the test.\n//\n// Note: to distinguish Win32 API calls from the local method and function\n// calls, the former are explicitly resolved in the global namespace.\n//\nclass WindowsDeathTest : public DeathTestImpl {\n public:\n WindowsDeathTest(const char* a_statement, Matcher matcher,\n const char* file, int line)\n : DeathTestImpl(a_statement, std::move(matcher)),\n file_(file),\n line_(line) {}\n\n // All of these virtual functions are inherited from DeathTest.\n virtual int Wait();\n virtual TestRole AssumeRole();\n\n private:\n // The name of the file in which the death test is located.\n const char* const file_;\n // The line number on which the death test is located.\n const int line_;\n // Handle to the write end of the pipe to the child process.\n AutoHandle write_handle_;\n // Child process handle.\n AutoHandle child_handle_;\n // Event the child process uses to signal the parent that it has\n // acquired the handle to the write end of the pipe. After seeing this\n // event the parent can release its own handles to make sure its\n // ReadFile() calls return when the child terminates.\n AutoHandle event_handle_;\n};\n\n// Waits for the child in a death test to exit, returning its exit\n// status, or 0 if no child process exists. As a side effect, sets the\n// outcome data member.\nint WindowsDeathTest::Wait() {\n if (!spawned())\n return 0;\n\n // Wait until the child either signals that it has acquired the write end\n // of the pipe or it dies.\n const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };\n switch (::WaitForMultipleObjects(2,\n wait_handles,\n FALSE, // Waits for any of the handles.\n INFINITE)) {\n case WAIT_OBJECT_0:\n case WAIT_OBJECT_0 + 1:\n break;\n default:\n GTEST_DEATH_TEST_CHECK_(false); // Should not get here.\n }\n\n // The child has acquired the write end of the pipe or exited.\n // We release the handle on our side and continue.\n write_handle_.Reset();\n event_handle_.Reset();\n\n ReadAndInterpretStatusByte();\n\n // Waits for the child process to exit if it haven't already. This\n // returns immediately if the child has already exited, regardless of\n // whether previous calls to WaitForMultipleObjects synchronized on this\n // handle or not.\n GTEST_DEATH_TEST_CHECK_(\n WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),\n INFINITE));\n DWORD status_code;\n GTEST_DEATH_TEST_CHECK_(\n ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);\n child_handle_.Reset();\n set_status(static_cast(status_code));\n return status();\n}\n\n// The AssumeRole process for a Windows death test. It creates a child\n// process with the same executable as the current process to run the\n// death test. The child process is given the --gtest_filter and\n// --gtest_internal_run_death_test flags such that it knows to run the\n// current death test only.\nDeathTest::TestRole WindowsDeathTest::AssumeRole() {\n const UnitTestImpl* const impl = GetUnitTestImpl();\n const InternalRunDeathTestFlag* const flag =\n impl->internal_run_death_test_flag();\n const TestInfo* const info = impl->current_test_info();\n const int death_test_index = info->result()->death_test_count();\n\n if (flag != nullptr) {\n // ParseInternalRunDeathTestFlag() has performed all the necessary\n // processing.\n set_write_fd(flag->write_fd());\n return EXECUTE_TEST;\n }\n\n // WindowsDeathTest uses an anonymous pipe to communicate results of\n // a death test.\n SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES),\n nullptr, TRUE};\n HANDLE read_handle, write_handle;\n GTEST_DEATH_TEST_CHECK_(\n ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,\n 0) // Default buffer size.\n != FALSE);\n set_read_fd(::_open_osfhandle(reinterpret_cast(read_handle),\n O_RDONLY));\n write_handle_.Reset(write_handle);\n event_handle_.Reset(::CreateEvent(\n &handles_are_inheritable,\n TRUE, // The event will automatically reset to non-signaled state.\n FALSE, // The initial state is non-signalled.\n nullptr)); // The even is unnamed.\n GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != nullptr);\n const std::string filter_flag = std::string(\"--\") + GTEST_FLAG_PREFIX_ +\n kFilterFlag + \"=\" + info->test_suite_name() +\n \".\" + info->name();\n const std::string internal_flag =\n std::string(\"--\") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +\n \"=\" + file_ + \"|\" + StreamableToString(line_) + \"|\" +\n StreamableToString(death_test_index) + \"|\" +\n StreamableToString(static_cast(::GetCurrentProcessId())) +\n // size_t has the same width as pointers on both 32-bit and 64-bit\n // Windows platforms.\n // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.\n \"|\" + StreamableToString(reinterpret_cast(write_handle)) +\n \"|\" + StreamableToString(reinterpret_cast(event_handle_.Get()));\n\n char executable_path[_MAX_PATH + 1]; // NOLINT\n GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(nullptr,\n executable_path,\n _MAX_PATH));\n\n std::string command_line =\n std::string(::GetCommandLineA()) + \" \" + filter_flag + \" \\\"\" +\n internal_flag + \"\\\"\";\n\n DeathTest::set_last_death_test_message(\"\");\n\n CaptureStderr();\n // Flush the log buffers since the log streams are shared with the child.\n FlushInfoLog();\n\n // The child process will share the standard handles with the parent.\n STARTUPINFOA startup_info;\n memset(&startup_info, 0, sizeof(STARTUPINFO));\n startup_info.dwFlags = STARTF_USESTDHANDLES;\n startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);\n startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);\n startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);\n\n PROCESS_INFORMATION process_info;\n GTEST_DEATH_TEST_CHECK_(\n ::CreateProcessA(\n executable_path, const_cast(command_line.c_str()),\n nullptr, // Retuned process handle is not inheritable.\n nullptr, // Retuned thread handle is not inheritable.\n TRUE, // Child inherits all inheritable handles (for write_handle_).\n 0x0, // Default creation flags.\n nullptr, // Inherit the parent's environment.\n UnitTest::GetInstance()->original_working_dir(), &startup_info,\n &process_info) != FALSE);\n child_handle_.Reset(process_info.hProcess);\n ::CloseHandle(process_info.hThread);\n set_spawned(true);\n return OVERSEE_TEST;\n}\n\n# elif GTEST_OS_FUCHSIA\n\nclass FuchsiaDeathTest : public DeathTestImpl {\n public:\n FuchsiaDeathTest(const char* a_statement, Matcher matcher,\n const char* file, int line)\n : DeathTestImpl(a_statement, std::move(matcher)),\n file_(file),\n line_(line) {}\n\n // All of these virtual functions are inherited from DeathTest.\n int Wait() override;\n TestRole AssumeRole() override;\n std::string GetErrorLogs() override;\n\n private:\n // The name of the file in which the death test is located.\n const char* const file_;\n // The line number on which the death test is located.\n const int line_;\n // The stderr data captured by the child process.\n std::string captured_stderr_;\n\n zx::process child_process_;\n zx::channel exception_channel_;\n zx::socket stderr_socket_;\n};\n\n// Utility class for accumulating command-line arguments.\nclass Arguments {\n public:\n Arguments() { args_.push_back(nullptr); }\n\n ~Arguments() {\n for (std::vector::iterator i = args_.begin(); i != args_.end();\n ++i) {\n free(*i);\n }\n }\n void AddArgument(const char* argument) {\n args_.insert(args_.end() - 1, posix::StrDup(argument));\n }\n\n template \n void AddArguments(const ::std::vector& arguments) {\n for (typename ::std::vector::const_iterator i = arguments.begin();\n i != arguments.end();\n ++i) {\n args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));\n }\n }\n char* const* Argv() {\n return &args_[0];\n }\n\n int size() {\n return static_cast(args_.size()) - 1;\n }\n\n private:\n std::vector args_;\n};\n\n// Waits for the child in a death test to exit, returning its exit\n// status, or 0 if no child process exists. As a side effect, sets the\n// outcome data member.\nint FuchsiaDeathTest::Wait() {\n const int kProcessKey = 0;\n const int kSocketKey = 1;\n const int kExceptionKey = 2;\n\n if (!spawned())\n return 0;\n\n // Create a port to wait for socket/task/exception events.\n zx_status_t status_zx;\n zx::port port;\n status_zx = zx::port::create(0, &port);\n GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);\n\n // Register to wait for the child process to terminate.\n status_zx = child_process_.wait_async(\n port, kProcessKey, ZX_PROCESS_TERMINATED, 0);\n GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);\n\n // Register to wait for the socket to be readable or closed.\n status_zx = stderr_socket_.wait_async(\n port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0);\n GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);\n\n // Register to wait for an exception.\n status_zx = exception_channel_.wait_async(\n port, kExceptionKey, ZX_CHANNEL_READABLE, 0);\n GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);\n\n bool process_terminated = false;\n bool socket_closed = false;\n do {\n zx_port_packet_t packet = {};\n status_zx = port.wait(zx::time::infinite(), &packet);\n GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);\n\n if (packet.key == kExceptionKey) {\n // Process encountered an exception. Kill it directly rather than\n // letting other handlers process the event. We will get a kProcessKey\n // event when the process actually terminates.\n status_zx = child_process_.kill();\n GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);\n } else if (packet.key == kProcessKey) {\n // Process terminated.\n GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));\n GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED);\n process_terminated = true;\n } else if (packet.key == kSocketKey) {\n GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));\n if (packet.signal.observed & ZX_SOCKET_READABLE) {\n // Read data from the socket.\n constexpr size_t kBufferSize = 1024;\n do {\n size_t old_length = captured_stderr_.length();\n size_t bytes_read = 0;\n captured_stderr_.resize(old_length + kBufferSize);\n status_zx = stderr_socket_.read(\n 0, &captured_stderr_.front() + old_length, kBufferSize,\n &bytes_read);\n captured_stderr_.resize(old_length + bytes_read);\n } while (status_zx == ZX_OK);\n if (status_zx == ZX_ERR_PEER_CLOSED) {\n socket_closed = true;\n } else {\n GTEST_DEATH_TEST_CHECK_(status_zx == ZX_ERR_SHOULD_WAIT);\n status_zx = stderr_socket_.wait_async(\n port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0);\n GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);\n }\n } else {\n GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_SOCKET_PEER_CLOSED);\n socket_closed = true;\n }\n }\n } while (!process_terminated && !socket_closed);\n\n ReadAndInterpretStatusByte();\n\n zx_info_process_v2_t buffer;\n status_zx = child_process_.get_info(\n ZX_INFO_PROCESS_V2, &buffer, sizeof(buffer), nullptr, nullptr);\n GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);\n\n GTEST_DEATH_TEST_CHECK_(buffer.flags & ZX_INFO_PROCESS_FLAG_EXITED);\n set_status(static_cast(buffer.return_code));\n return status();\n}\n\n// The AssumeRole process for a Fuchsia death test. It creates a child\n// process with the same executable as the current process to run the\n// death test. The child process is given the --gtest_filter and\n// --gtest_internal_run_death_test flags such that it knows to run the\n// current death test only.\nDeathTest::TestRole FuchsiaDeathTest::AssumeRole() {\n const UnitTestImpl* const impl = GetUnitTestImpl();\n const InternalRunDeathTestFlag* const flag =\n impl->internal_run_death_test_flag();\n const TestInfo* const info = impl->current_test_info();\n const int death_test_index = info->result()->death_test_count();\n\n if (flag != nullptr) {\n // ParseInternalRunDeathTestFlag() has performed all the necessary\n // processing.\n set_write_fd(kFuchsiaReadPipeFd);\n return EXECUTE_TEST;\n }\n\n // Flush the log buffers since the log streams are shared with the child.\n FlushInfoLog();\n\n // Build the child process command line.\n const std::string filter_flag = std::string(\"--\") + GTEST_FLAG_PREFIX_ +\n kFilterFlag + \"=\" + info->test_suite_name() +\n \".\" + info->name();\n const std::string internal_flag =\n std::string(\"--\") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + \"=\"\n + file_ + \"|\"\n + StreamableToString(line_) + \"|\"\n + StreamableToString(death_test_index);\n Arguments args;\n args.AddArguments(GetInjectableArgvs());\n args.AddArgument(filter_flag.c_str());\n args.AddArgument(internal_flag.c_str());\n\n // Build the pipe for communication with the child.\n zx_status_t status;\n zx_handle_t child_pipe_handle;\n int child_pipe_fd;\n status = fdio_pipe_half(&child_pipe_fd, &child_pipe_handle);\n GTEST_DEATH_TEST_CHECK_(status == ZX_OK);\n set_read_fd(child_pipe_fd);\n\n // Set the pipe handle for the child.\n fdio_spawn_action_t spawn_actions[2] = {};\n fdio_spawn_action_t* add_handle_action = &spawn_actions[0];\n add_handle_action->action = FDIO_SPAWN_ACTION_ADD_HANDLE;\n add_handle_action->h.id = PA_HND(PA_FD, kFuchsiaReadPipeFd);\n add_handle_action->h.handle = child_pipe_handle;\n\n // Create a socket pair will be used to receive the child process' stderr.\n zx::socket stderr_producer_socket;\n status =\n zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);\n GTEST_DEATH_TEST_CHECK_(status >= 0);\n int stderr_producer_fd = -1;\n status =\n fdio_fd_create(stderr_producer_socket.release(), &stderr_producer_fd);\n GTEST_DEATH_TEST_CHECK_(status >= 0);\n\n // Make the stderr socket nonblocking.\n GTEST_DEATH_TEST_CHECK_(fcntl(stderr_producer_fd, F_SETFL, 0) == 0);\n\n fdio_spawn_action_t* add_stderr_action = &spawn_actions[1];\n add_stderr_action->action = FDIO_SPAWN_ACTION_CLONE_FD;\n add_stderr_action->fd.local_fd = stderr_producer_fd;\n add_stderr_action->fd.target_fd = STDERR_FILENO;\n\n // Create a child job.\n zx_handle_t child_job = ZX_HANDLE_INVALID;\n status = zx_job_create(zx_job_default(), 0, & child_job);\n GTEST_DEATH_TEST_CHECK_(status == ZX_OK);\n zx_policy_basic_t policy;\n policy.condition = ZX_POL_NEW_ANY;\n policy.policy = ZX_POL_ACTION_ALLOW;\n status = zx_job_set_policy(\n child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, &policy, 1);\n GTEST_DEATH_TEST_CHECK_(status == ZX_OK);\n\n // Create an exception channel attached to the |child_job|, to allow\n // us to suppress the system default exception handler from firing.\n status =\n zx_task_create_exception_channel(\n child_job, 0, exception_channel_.reset_and_get_address());\n GTEST_DEATH_TEST_CHECK_(status == ZX_OK);\n\n // Spawn the child process.\n status = fdio_spawn_etc(\n child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(), nullptr,\n 2, spawn_actions, child_process_.reset_and_get_address(), nullptr);\n GTEST_DEATH_TEST_CHECK_(status == ZX_OK);\n\n set_spawned(true);\n return OVERSEE_TEST;\n}\n\nstd::string FuchsiaDeathTest::GetErrorLogs() {\n return captured_stderr_;\n}\n\n#else // We are neither on Windows, nor on Fuchsia.\n\n// ForkingDeathTest provides implementations for most of the abstract\n// methods of the DeathTest interface. Only the AssumeRole method is\n// left undefined.\nclass ForkingDeathTest : public DeathTestImpl {\n public:\n ForkingDeathTest(const char* statement, Matcher matcher);\n\n // All of these virtual functions are inherited from DeathTest.\n int Wait() override;\n\n protected:\n void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }\n\n private:\n // PID of child process during death test; 0 in the child process itself.\n pid_t child_pid_;\n};\n\n// Constructs a ForkingDeathTest.\nForkingDeathTest::ForkingDeathTest(const char* a_statement,\n Matcher matcher)\n : DeathTestImpl(a_statement, std::move(matcher)), child_pid_(-1) {}\n\n// Waits for the child in a death test to exit, returning its exit\n// status, or 0 if no child process exists. As a side effect, sets the\n// outcome data member.\nint ForkingDeathTest::Wait() {\n if (!spawned())\n return 0;\n\n ReadAndInterpretStatusByte();\n\n int status_value;\n GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));\n set_status(status_value);\n return status_value;\n}\n\n// A concrete death test class that forks, then immediately runs the test\n// in the child process.\nclass NoExecDeathTest : public ForkingDeathTest {\n public:\n NoExecDeathTest(const char* a_statement, Matcher matcher)\n : ForkingDeathTest(a_statement, std::move(matcher)) {}\n TestRole AssumeRole() override;\n};\n\n// The AssumeRole process for a fork-and-run death test. It implements a\n// straightforward fork, with a simple pipe to transmit the status byte.\nDeathTest::TestRole NoExecDeathTest::AssumeRole() {\n const size_t thread_count = GetThreadCount();\n if (thread_count != 1) {\n GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);\n }\n\n int pipe_fd[2];\n GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);\n\n DeathTest::set_last_death_test_message(\"\");\n CaptureStderr();\n // When we fork the process below, the log file buffers are copied, but the\n // file descriptors are shared. We flush all log files here so that closing\n // the file descriptors in the child process doesn't throw off the\n // synchronization between descriptors and buffers in the parent process.\n // This is as close to the fork as possible to avoid a race condition in case\n // there are multiple threads running before the death test, and another\n // thread writes to the log file.\n FlushInfoLog();\n\n const pid_t child_pid = fork();\n GTEST_DEATH_TEST_CHECK_(child_pid != -1);\n set_child_pid(child_pid);\n if (child_pid == 0) {\n GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));\n set_write_fd(pipe_fd[1]);\n // Redirects all logging to stderr in the child process to prevent\n // concurrent writes to the log files. We capture stderr in the parent\n // process and append the child process' output to a log.\n LogToStderr();\n // Event forwarding to the listeners of event listener API mush be shut\n // down in death test subprocesses.\n GetUnitTestImpl()->listeners()->SuppressEventForwarding();\n g_in_fast_death_test_child = true;\n return EXECUTE_TEST;\n } else {\n GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));\n set_read_fd(pipe_fd[0]);\n set_spawned(true);\n return OVERSEE_TEST;\n }\n}\n\n// A concrete death test class that forks and re-executes the main\n// program from the beginning, with command-line flags set that cause\n// only this specific death test to be run.\nclass ExecDeathTest : public ForkingDeathTest {\n public:\n ExecDeathTest(const char* a_statement, Matcher matcher,\n const char* file, int line)\n : ForkingDeathTest(a_statement, std::move(matcher)),\n file_(file),\n line_(line) {}\n TestRole AssumeRole() override;\n\n private:\n static ::std::vector GetArgvsForDeathTestChildProcess() {\n ::std::vector args = GetInjectableArgvs();\n# if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)\n ::std::vector extra_args =\n GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();\n args.insert(args.end(), extra_args.begin(), extra_args.end());\n# endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)\n return args;\n }\n // The name of the file in which the death test is located.\n const char* const file_;\n // The line number on which the death test is located.\n const int line_;\n};\n\n// Utility class for accumulating command-line arguments.\nclass Arguments {\n public:\n Arguments() { args_.push_back(nullptr); }\n\n ~Arguments() {\n for (std::vector::iterator i = args_.begin(); i != args_.end();\n ++i) {\n free(*i);\n }\n }\n void AddArgument(const char* argument) {\n args_.insert(args_.end() - 1, posix::StrDup(argument));\n }\n\n template \n void AddArguments(const ::std::vector& arguments) {\n for (typename ::std::vector::const_iterator i = arguments.begin();\n i != arguments.end();\n ++i) {\n args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));\n }\n }\n char* const* Argv() {\n return &args_[0];\n }\n\n private:\n std::vector args_;\n};\n\n// A struct that encompasses the arguments to the child process of a\n// threadsafe-style death test process.\nstruct ExecDeathTestArgs {\n char* const* argv; // Command-line arguments for the child's call to exec\n int close_fd; // File descriptor to close; the read end of a pipe\n};\n\n# if GTEST_OS_QNX\nextern \"C\" char** environ;\n# else // GTEST_OS_QNX\n// The main function for a threadsafe-style death test child process.\n// This function is called in a clone()-ed process and thus must avoid\n// any potentially unsafe operations like malloc or libc functions.\nstatic int ExecDeathTestChildMain(void* child_arg) {\n ExecDeathTestArgs* const args = static_cast(child_arg);\n GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));\n\n // We need to execute the test program in the same environment where\n // it was originally invoked. Therefore we change to the original\n // working directory first.\n const char* const original_dir =\n UnitTest::GetInstance()->original_working_dir();\n // We can safely call chdir() as it's a direct system call.\n if (chdir(original_dir) != 0) {\n DeathTestAbort(std::string(\"chdir(\\\"\") + original_dir + \"\\\") failed: \" +\n GetLastErrnoDescription());\n return EXIT_FAILURE;\n }\n\n // We can safely call execv() as it's almost a direct system call. We\n // cannot use execvp() as it's a libc function and thus potentially\n // unsafe. Since execv() doesn't search the PATH, the user must\n // invoke the test program via a valid path that contains at least\n // one path separator.\n execv(args->argv[0], args->argv);\n DeathTestAbort(std::string(\"execv(\") + args->argv[0] + \", ...) in \" +\n original_dir + \" failed: \" +\n GetLastErrnoDescription());\n return EXIT_FAILURE;\n}\n# endif // GTEST_OS_QNX\n\n# if GTEST_HAS_CLONE\n// Two utility routines that together determine the direction the stack\n// grows.\n// This could be accomplished more elegantly by a single recursive\n// function, but we want to guard against the unlikely possibility of\n// a smart compiler optimizing the recursion away.\n//\n// GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining\n// StackLowerThanAddress into StackGrowsDown, which then doesn't give\n// correct answer.\nstatic void StackLowerThanAddress(const void* ptr,\n bool* result) GTEST_NO_INLINE_;\n// Make sure sanitizers do not tamper with the stack here.\n// Ideally, we want to use `__builtin_frame_address` instead of a local variable\n// address with sanitizer disabled, but it does not work when the\n// compiler optimizes the stack frame out, which happens on PowerPC targets.\n// HWAddressSanitizer add a random tag to the MSB of the local variable address,\n// making comparison result unpredictable.\nGTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_\nGTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_\nstatic void StackLowerThanAddress(const void* ptr, bool* result) {\n int dummy = 0;\n *result = std::less()(&dummy, ptr);\n}\n\n// Make sure AddressSanitizer does not tamper with the stack here.\nGTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_\nGTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_\nstatic bool StackGrowsDown() {\n int dummy = 0;\n bool result;\n StackLowerThanAddress(&dummy, &result);\n return result;\n}\n# endif // GTEST_HAS_CLONE\n\n// Spawns a child process with the same executable as the current process in\n// a thread-safe manner and instructs it to run the death test. The\n// implementation uses fork(2) + exec. On systems where clone(2) is\n// available, it is used instead, being slightly more thread-safe. On QNX,\n// fork supports only single-threaded environments, so this function uses\n// spawn(2) there instead. The function dies with an error message if\n// anything goes wrong.\nstatic pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {\n ExecDeathTestArgs args = { argv, close_fd };\n pid_t child_pid = -1;\n\n# if GTEST_OS_QNX\n // Obtains the current directory and sets it to be closed in the child\n // process.\n const int cwd_fd = open(\".\", O_RDONLY);\n GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);\n GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));\n // We need to execute the test program in the same environment where\n // it was originally invoked. Therefore we change to the original\n // working directory first.\n const char* const original_dir =\n UnitTest::GetInstance()->original_working_dir();\n // We can safely call chdir() as it's a direct system call.\n if (chdir(original_dir) != 0) {\n DeathTestAbort(std::string(\"chdir(\\\"\") + original_dir + \"\\\") failed: \" +\n GetLastErrnoDescription());\n return EXIT_FAILURE;\n }\n\n int fd_flags;\n // Set close_fd to be closed after spawn.\n GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));\n GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,\n fd_flags | FD_CLOEXEC));\n struct inheritance inherit = {0};\n // spawn is a system call.\n child_pid = spawn(args.argv[0], 0, nullptr, &inherit, args.argv, environ);\n // Restores the current working directory.\n GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);\n GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));\n\n# else // GTEST_OS_QNX\n# if GTEST_OS_LINUX\n // When a SIGPROF signal is received while fork() or clone() are executing,\n // the process may hang. To avoid this, we ignore SIGPROF here and re-enable\n // it after the call to fork()/clone() is complete.\n struct sigaction saved_sigprof_action;\n struct sigaction ignore_sigprof_action;\n memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));\n sigemptyset(&ignore_sigprof_action.sa_mask);\n ignore_sigprof_action.sa_handler = SIG_IGN;\n GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(\n SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));\n# endif // GTEST_OS_LINUX\n\n# if GTEST_HAS_CLONE\n const bool use_fork = GTEST_FLAG(death_test_use_fork);\n\n if (!use_fork) {\n static const bool stack_grows_down = StackGrowsDown();\n const auto stack_size = static_cast(getpagesize() * 2);\n // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.\n void* const stack = mmap(nullptr, stack_size, PROT_READ | PROT_WRITE,\n MAP_ANON | MAP_PRIVATE, -1, 0);\n GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);\n\n // Maximum stack alignment in bytes: For a downward-growing stack, this\n // amount is subtracted from size of the stack space to get an address\n // that is within the stack space and is aligned on all systems we care\n // about. As far as I know there is no ABI with stack alignment greater\n // than 64. We assume stack and stack_size already have alignment of\n // kMaxStackAlignment.\n const size_t kMaxStackAlignment = 64;\n void* const stack_top =\n static_cast(stack) +\n (stack_grows_down ? stack_size - kMaxStackAlignment : 0);\n GTEST_DEATH_TEST_CHECK_(\n static_cast(stack_size) > kMaxStackAlignment &&\n reinterpret_cast(stack_top) % kMaxStackAlignment == 0);\n\n child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);\n\n GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);\n }\n# else\n const bool use_fork = true;\n# endif // GTEST_HAS_CLONE\n\n if (use_fork && (child_pid = fork()) == 0) {\n ExecDeathTestChildMain(&args);\n _exit(0);\n }\n# endif // GTEST_OS_QNX\n# if GTEST_OS_LINUX\n GTEST_DEATH_TEST_CHECK_SYSCALL_(\n sigaction(SIGPROF, &saved_sigprof_action, nullptr));\n# endif // GTEST_OS_LINUX\n\n GTEST_DEATH_TEST_CHECK_(child_pid != -1);\n return child_pid;\n}\n\n// The AssumeRole process for a fork-and-exec death test. It re-executes the\n// main program from the beginning, setting the --gtest_filter\n// and --gtest_internal_run_death_test flags to cause only the current\n// death test to be re-run.\nDeathTest::TestRole ExecDeathTest::AssumeRole() {\n const UnitTestImpl* const impl = GetUnitTestImpl();\n const InternalRunDeathTestFlag* const flag =\n impl->internal_run_death_test_flag();\n const TestInfo* const info = impl->current_test_info();\n const int death_test_index = info->result()->death_test_count();\n\n if (flag != nullptr) {\n set_write_fd(flag->write_fd());\n return EXECUTE_TEST;\n }\n\n int pipe_fd[2];\n GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);\n // Clear the close-on-exec flag on the write end of the pipe, lest\n // it be closed when the child process does an exec:\n GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);\n\n const std::string filter_flag = std::string(\"--\") + GTEST_FLAG_PREFIX_ +\n kFilterFlag + \"=\" + info->test_suite_name() +\n \".\" + info->name();\n const std::string internal_flag =\n std::string(\"--\") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + \"=\"\n + file_ + \"|\" + StreamableToString(line_) + \"|\"\n + StreamableToString(death_test_index) + \"|\"\n + StreamableToString(pipe_fd[1]);\n Arguments args;\n args.AddArguments(GetArgvsForDeathTestChildProcess());\n args.AddArgument(filter_flag.c_str());\n args.AddArgument(internal_flag.c_str());\n\n DeathTest::set_last_death_test_message(\"\");\n\n CaptureStderr();\n // See the comment in NoExecDeathTest::AssumeRole for why the next line\n // is necessary.\n FlushInfoLog();\n\n const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);\n GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));\n set_child_pid(child_pid);\n set_read_fd(pipe_fd[0]);\n set_spawned(true);\n return OVERSEE_TEST;\n}\n\n# endif // !GTEST_OS_WINDOWS\n\n// Creates a concrete DeathTest-derived class that depends on the\n// --gtest_death_test_style flag, and sets the pointer pointed to\n// by the \"test\" argument to its address. If the test should be\n// skipped, sets that pointer to NULL. Returns true, unless the\n// flag is set to an invalid value.\nbool DefaultDeathTestFactory::Create(const char* statement,\n Matcher matcher,\n const char* file, int line,\n DeathTest** test) {\n UnitTestImpl* const impl = GetUnitTestImpl();\n const InternalRunDeathTestFlag* const flag =\n impl->internal_run_death_test_flag();\n const int death_test_index = impl->current_test_info()\n ->increment_death_test_count();\n\n if (flag != nullptr) {\n if (death_test_index > flag->index()) {\n DeathTest::set_last_death_test_message(\n \"Death test count (\" + StreamableToString(death_test_index)\n + \") somehow exceeded expected maximum (\"\n + StreamableToString(flag->index()) + \")\");\n return false;\n }\n\n if (!(flag->file() == file && flag->line() == line &&\n flag->index() == death_test_index)) {\n *test = nullptr;\n return true;\n }\n }\n\n# if GTEST_OS_WINDOWS\n\n if (GTEST_FLAG(death_test_style) == \"threadsafe\" ||\n GTEST_FLAG(death_test_style) == \"fast\") {\n *test = new WindowsDeathTest(statement, std::move(matcher), file, line);\n }\n\n# elif GTEST_OS_FUCHSIA\n\n if (GTEST_FLAG(death_test_style) == \"threadsafe\" ||\n GTEST_FLAG(death_test_style) == \"fast\") {\n *test = new FuchsiaDeathTest(statement, std::move(matcher), file, line);\n }\n\n# else\n\n if (GTEST_FLAG(death_test_style) == \"threadsafe\") {\n *test = new ExecDeathTest(statement, std::move(matcher), file, line);\n } else if (GTEST_FLAG(death_test_style) == \"fast\") {\n *test = new NoExecDeathTest(statement, std::move(matcher));\n }\n\n# endif // GTEST_OS_WINDOWS\n\n else { // NOLINT - this is more readable than unbalanced brackets inside #if.\n DeathTest::set_last_death_test_message(\n \"Unknown death test style \\\"\" + GTEST_FLAG(death_test_style)\n + \"\\\" encountered\");\n return false;\n }\n\n return true;\n}\n\n# if GTEST_OS_WINDOWS\n// Recreates the pipe and event handles from the provided parameters,\n// signals the event, and returns a file descriptor wrapped around the pipe\n// handle. This function is called in the child process only.\nstatic int GetStatusFileDescriptor(unsigned int parent_process_id,\n size_t write_handle_as_size_t,\n size_t event_handle_as_size_t) {\n AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,\n FALSE, // Non-inheritable.\n parent_process_id));\n if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {\n DeathTestAbort(\"Unable to open parent process \" +\n StreamableToString(parent_process_id));\n }\n\n GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));\n\n const HANDLE write_handle =\n reinterpret_cast(write_handle_as_size_t);\n HANDLE dup_write_handle;\n\n // The newly initialized handle is accessible only in the parent\n // process. To obtain one accessible within the child, we need to use\n // DuplicateHandle.\n if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,\n ::GetCurrentProcess(), &dup_write_handle,\n 0x0, // Requested privileges ignored since\n // DUPLICATE_SAME_ACCESS is used.\n FALSE, // Request non-inheritable handler.\n DUPLICATE_SAME_ACCESS)) {\n DeathTestAbort(\"Unable to duplicate the pipe handle \" +\n StreamableToString(write_handle_as_size_t) +\n \" from the parent process \" +\n StreamableToString(parent_process_id));\n }\n\n const HANDLE event_handle = reinterpret_cast(event_handle_as_size_t);\n HANDLE dup_event_handle;\n\n if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,\n ::GetCurrentProcess(), &dup_event_handle,\n 0x0,\n FALSE,\n DUPLICATE_SAME_ACCESS)) {\n DeathTestAbort(\"Unable to duplicate the event handle \" +\n StreamableToString(event_handle_as_size_t) +\n \" from the parent process \" +\n StreamableToString(parent_process_id));\n }\n\n const int write_fd =\n ::_open_osfhandle(reinterpret_cast(dup_write_handle), O_APPEND);\n if (write_fd == -1) {\n DeathTestAbort(\"Unable to convert pipe handle \" +\n StreamableToString(write_handle_as_size_t) +\n \" to a file descriptor\");\n }\n\n // Signals the parent that the write end of the pipe has been acquired\n // so the parent can release its own write end.\n ::SetEvent(dup_event_handle);\n\n return write_fd;\n}\n# endif // GTEST_OS_WINDOWS\n\n// Returns a newly created InternalRunDeathTestFlag object with fields\n// initialized from the GTEST_FLAG(internal_run_death_test) flag if\n// the flag is specified; otherwise returns NULL.\nInternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {\n if (GTEST_FLAG(internal_run_death_test) == \"\") return nullptr;\n\n // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we\n // can use it here.\n int line = -1;\n int index = -1;\n ::std::vector< ::std::string> fields;\n SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);\n int write_fd = -1;\n\n# if GTEST_OS_WINDOWS\n\n unsigned int parent_process_id = 0;\n size_t write_handle_as_size_t = 0;\n size_t event_handle_as_size_t = 0;\n\n if (fields.size() != 6\n || !ParseNaturalNumber(fields[1], &line)\n || !ParseNaturalNumber(fields[2], &index)\n || !ParseNaturalNumber(fields[3], &parent_process_id)\n || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)\n || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {\n DeathTestAbort(\"Bad --gtest_internal_run_death_test flag: \" +\n GTEST_FLAG(internal_run_death_test));\n }\n write_fd = GetStatusFileDescriptor(parent_process_id,\n write_handle_as_size_t,\n event_handle_as_size_t);\n\n# elif GTEST_OS_FUCHSIA\n\n if (fields.size() != 3\n || !ParseNaturalNumber(fields[1], &line)\n || !ParseNaturalNumber(fields[2], &index)) {\n DeathTestAbort(\"Bad --gtest_internal_run_death_test flag: \"\n + GTEST_FLAG(internal_run_death_test));\n }\n\n# else\n\n if (fields.size() != 4\n || !ParseNaturalNumber(fields[1], &line)\n || !ParseNaturalNumber(fields[2], &index)\n || !ParseNaturalNumber(fields[3], &write_fd)) {\n DeathTestAbort(\"Bad --gtest_internal_run_death_test flag: \"\n + GTEST_FLAG(internal_run_death_test));\n }\n\n# endif // GTEST_OS_WINDOWS\n\n return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);\n}\n\n} // namespace internal\n\n#endif // GTEST_HAS_DEATH_TEST\n\n} // namespace testing\n// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n#include \n\n#if GTEST_OS_WINDOWS_MOBILE\n# include \n#elif GTEST_OS_WINDOWS\n# include \n# include \n#else\n# include \n# include // Some Linux distributions define PATH_MAX here.\n#endif // GTEST_OS_WINDOWS_MOBILE\n\n\n#if GTEST_OS_WINDOWS\n# define GTEST_PATH_MAX_ _MAX_PATH\n#elif defined(PATH_MAX)\n# define GTEST_PATH_MAX_ PATH_MAX\n#elif defined(_XOPEN_PATH_MAX)\n# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX\n#else\n# define GTEST_PATH_MAX_ _POSIX_PATH_MAX\n#endif // GTEST_OS_WINDOWS\n\nnamespace testing {\nnamespace internal {\n\n#if GTEST_OS_WINDOWS\n// On Windows, '\\\\' is the standard path separator, but many tools and the\n// Windows API also accept '/' as an alternate path separator. Unless otherwise\n// noted, a file path can contain either kind of path separators, or a mixture\n// of them.\nconst char kPathSeparator = '\\\\';\nconst char kAlternatePathSeparator = '/';\nconst char kAlternatePathSeparatorString[] = \"/\";\n# if GTEST_OS_WINDOWS_MOBILE\n// Windows CE doesn't have a current directory. You should not use\n// the current directory in tests on Windows CE, but this at least\n// provides a reasonable fallback.\nconst char kCurrentDirectoryString[] = \"\\\\\";\n// Windows CE doesn't define INVALID_FILE_ATTRIBUTES\nconst DWORD kInvalidFileAttributes = 0xffffffff;\n# else\nconst char kCurrentDirectoryString[] = \".\\\\\";\n# endif // GTEST_OS_WINDOWS_MOBILE\n#else\nconst char kPathSeparator = '/';\nconst char kCurrentDirectoryString[] = \"./\";\n#endif // GTEST_OS_WINDOWS\n\n// Returns whether the given character is a valid path separator.\nstatic bool IsPathSeparator(char c) {\n#if GTEST_HAS_ALT_PATH_SEP_\n return (c == kPathSeparator) || (c == kAlternatePathSeparator);\n#else\n return c == kPathSeparator;\n#endif\n}\n\n// Returns the current working directory, or \"\" if unsuccessful.\nFilePath FilePath::GetCurrentDir() {\n#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \\\n GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_ESP32 || \\\n GTEST_OS_XTENSA\n // These platforms do not have a current directory, so we just return\n // something reasonable.\n return FilePath(kCurrentDirectoryString);\n#elif GTEST_OS_WINDOWS\n char cwd[GTEST_PATH_MAX_ + 1] = { '\\0' };\n return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? \"\" : cwd);\n#else\n char cwd[GTEST_PATH_MAX_ + 1] = { '\\0' };\n char* result = getcwd(cwd, sizeof(cwd));\n# if GTEST_OS_NACL\n // getcwd will likely fail in NaCl due to the sandbox, so return something\n // reasonable. The user may have provided a shim implementation for getcwd,\n // however, so fallback only when failure is detected.\n return FilePath(result == nullptr ? kCurrentDirectoryString : cwd);\n# endif // GTEST_OS_NACL\n return FilePath(result == nullptr ? \"\" : cwd);\n#endif // GTEST_OS_WINDOWS_MOBILE\n}\n\n// Returns a copy of the FilePath with the case-insensitive extension removed.\n// Example: FilePath(\"dir/file.exe\").RemoveExtension(\"EXE\") returns\n// FilePath(\"dir/file\"). If a case-insensitive extension is not\n// found, returns a copy of the original FilePath.\nFilePath FilePath::RemoveExtension(const char* extension) const {\n const std::string dot_extension = std::string(\".\") + extension;\n if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {\n return FilePath(pathname_.substr(\n 0, pathname_.length() - dot_extension.length()));\n }\n return *this;\n}\n\n// Returns a pointer to the last occurrence of a valid path separator in\n// the FilePath. On Windows, for example, both '/' and '\\' are valid path\n// separators. Returns NULL if no path separator was found.\nconst char* FilePath::FindLastPathSeparator() const {\n const char* const last_sep = strrchr(c_str(), kPathSeparator);\n#if GTEST_HAS_ALT_PATH_SEP_\n const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);\n // Comparing two pointers of which only one is NULL is undefined.\n if (last_alt_sep != nullptr &&\n (last_sep == nullptr || last_alt_sep > last_sep)) {\n return last_alt_sep;\n }\n#endif\n return last_sep;\n}\n\n// Returns a copy of the FilePath with the directory part removed.\n// Example: FilePath(\"path/to/file\").RemoveDirectoryName() returns\n// FilePath(\"file\"). If there is no directory part (\"just_a_file\"), it returns\n// the FilePath unmodified. If there is no file part (\"just_a_dir/\") it\n// returns an empty FilePath (\"\").\n// On Windows platform, '\\' is the path separator, otherwise it is '/'.\nFilePath FilePath::RemoveDirectoryName() const {\n const char* const last_sep = FindLastPathSeparator();\n return last_sep ? FilePath(last_sep + 1) : *this;\n}\n\n// RemoveFileName returns the directory path with the filename removed.\n// Example: FilePath(\"path/to/file\").RemoveFileName() returns \"path/to/\".\n// If the FilePath is \"a_file\" or \"/a_file\", RemoveFileName returns\n// FilePath(\"./\") or, on Windows, FilePath(\".\\\\\"). If the filepath does\n// not have a file, like \"just/a/dir/\", it returns the FilePath unmodified.\n// On Windows platform, '\\' is the path separator, otherwise it is '/'.\nFilePath FilePath::RemoveFileName() const {\n const char* const last_sep = FindLastPathSeparator();\n std::string dir;\n if (last_sep) {\n dir = std::string(c_str(), static_cast(last_sep + 1 - c_str()));\n } else {\n dir = kCurrentDirectoryString;\n }\n return FilePath(dir);\n}\n\n// Helper functions for naming files in a directory for xml output.\n\n// Given directory = \"dir\", base_name = \"test\", number = 0,\n// extension = \"xml\", returns \"dir/test.xml\". If number is greater\n// than zero (e.g., 12), returns \"dir/test_12.xml\".\n// On Windows platform, uses \\ as the separator rather than /.\nFilePath FilePath::MakeFileName(const FilePath& directory,\n const FilePath& base_name,\n int number,\n const char* extension) {\n std::string file;\n if (number == 0) {\n file = base_name.string() + \".\" + extension;\n } else {\n file = base_name.string() + \"_\" + StreamableToString(number)\n + \".\" + extension;\n }\n return ConcatPaths(directory, FilePath(file));\n}\n\n// Given directory = \"dir\", relative_path = \"test.xml\", returns \"dir/test.xml\".\n// On Windows, uses \\ as the separator rather than /.\nFilePath FilePath::ConcatPaths(const FilePath& directory,\n const FilePath& relative_path) {\n if (directory.IsEmpty())\n return relative_path;\n const FilePath dir(directory.RemoveTrailingPathSeparator());\n return FilePath(dir.string() + kPathSeparator + relative_path.string());\n}\n\n// Returns true if pathname describes something findable in the file-system,\n// either a file, directory, or whatever.\nbool FilePath::FileOrDirectoryExists() const {\n#if GTEST_OS_WINDOWS_MOBILE\n LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());\n const DWORD attributes = GetFileAttributes(unicode);\n delete [] unicode;\n return attributes != kInvalidFileAttributes;\n#else\n posix::StatStruct file_stat;\n return posix::Stat(pathname_.c_str(), &file_stat) == 0;\n#endif // GTEST_OS_WINDOWS_MOBILE\n}\n\n// Returns true if pathname describes a directory in the file-system\n// that exists.\nbool FilePath::DirectoryExists() const {\n bool result = false;\n#if GTEST_OS_WINDOWS\n // Don't strip off trailing separator if path is a root directory on\n // Windows (like \"C:\\\\\").\n const FilePath& path(IsRootDirectory() ? *this :\n RemoveTrailingPathSeparator());\n#else\n const FilePath& path(*this);\n#endif\n\n#if GTEST_OS_WINDOWS_MOBILE\n LPCWSTR unicode = String::AnsiToUtf16(path.c_str());\n const DWORD attributes = GetFileAttributes(unicode);\n delete [] unicode;\n if ((attributes != kInvalidFileAttributes) &&\n (attributes & FILE_ATTRIBUTE_DIRECTORY)) {\n result = true;\n }\n#else\n posix::StatStruct file_stat;\n result = posix::Stat(path.c_str(), &file_stat) == 0 &&\n posix::IsDir(file_stat);\n#endif // GTEST_OS_WINDOWS_MOBILE\n\n return result;\n}\n\n// Returns true if pathname describes a root directory. (Windows has one\n// root directory per disk drive.)\nbool FilePath::IsRootDirectory() const {\n#if GTEST_OS_WINDOWS\n return pathname_.length() == 3 && IsAbsolutePath();\n#else\n return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);\n#endif\n}\n\n// Returns true if pathname describes an absolute path.\nbool FilePath::IsAbsolutePath() const {\n const char* const name = pathname_.c_str();\n#if GTEST_OS_WINDOWS\n return pathname_.length() >= 3 &&\n ((name[0] >= 'a' && name[0] <= 'z') ||\n (name[0] >= 'A' && name[0] <= 'Z')) &&\n name[1] == ':' &&\n IsPathSeparator(name[2]);\n#else\n return IsPathSeparator(name[0]);\n#endif\n}\n\n// Returns a pathname for a file that does not currently exist. The pathname\n// will be directory/base_name.extension or\n// directory/base_name_.extension if directory/base_name.extension\n// already exists. The number will be incremented until a pathname is found\n// that does not already exist.\n// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.\n// There could be a race condition if two or more processes are calling this\n// function at the same time -- they could both pick the same filename.\nFilePath FilePath::GenerateUniqueFileName(const FilePath& directory,\n const FilePath& base_name,\n const char* extension) {\n FilePath full_pathname;\n int number = 0;\n do {\n full_pathname.Set(MakeFileName(directory, base_name, number++, extension));\n } while (full_pathname.FileOrDirectoryExists());\n return full_pathname;\n}\n\n// Returns true if FilePath ends with a path separator, which indicates that\n// it is intended to represent a directory. Returns false otherwise.\n// This does NOT check that a directory (or file) actually exists.\nbool FilePath::IsDirectory() const {\n return !pathname_.empty() &&\n IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);\n}\n\n// Create directories so that path exists. Returns true if successful or if\n// the directories already exist; returns false if unable to create directories\n// for any reason.\nbool FilePath::CreateDirectoriesRecursively() const {\n if (!this->IsDirectory()) {\n return false;\n }\n\n if (pathname_.length() == 0 || this->DirectoryExists()) {\n return true;\n }\n\n const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());\n return parent.CreateDirectoriesRecursively() && this->CreateFolder();\n}\n\n// Create the directory so that path exists. Returns true if successful or\n// if the directory already exists; returns false if unable to create the\n// directory for any reason, including if the parent directory does not\n// exist. Not named \"CreateDirectory\" because that's a macro on Windows.\nbool FilePath::CreateFolder() const {\n#if GTEST_OS_WINDOWS_MOBILE\n FilePath removed_sep(this->RemoveTrailingPathSeparator());\n LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());\n int result = CreateDirectory(unicode, nullptr) ? 0 : -1;\n delete [] unicode;\n#elif GTEST_OS_WINDOWS\n int result = _mkdir(pathname_.c_str());\n#elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA\n // do nothing\n int result = 0;\n#else\n int result = mkdir(pathname_.c_str(), 0777);\n#endif // GTEST_OS_WINDOWS_MOBILE\n\n if (result == -1) {\n return this->DirectoryExists(); // An error is OK if the directory exists.\n }\n return true; // No error.\n}\n\n// If input name has a trailing separator character, remove it and return the\n// name, otherwise return the name string unmodified.\n// On Windows platform, uses \\ as the separator, other platforms use /.\nFilePath FilePath::RemoveTrailingPathSeparator() const {\n return IsDirectory()\n ? FilePath(pathname_.substr(0, pathname_.length() - 1))\n : *this;\n}\n\n// Removes any redundant separators that might be in the pathname.\n// For example, \"bar///foo\" becomes \"bar/foo\". Does not eliminate other\n// redundancies that might be in a pathname involving \".\" or \"..\".\nvoid FilePath::Normalize() {\n auto out = pathname_.begin();\n\n for (const char character : pathname_) {\n if (!IsPathSeparator(character)) {\n *(out++) = character;\n } else if (out == pathname_.begin() || *std::prev(out) != kPathSeparator) {\n *(out++) = kPathSeparator;\n } else {\n continue;\n }\n }\n\n pathname_.erase(out, pathname_.end());\n}\n\n} // namespace internal\n} // namespace testing\n// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// The Google C++ Testing and Mocking Framework (Google Test)\n//\n// This file implements just enough of the matcher interface to allow\n// EXPECT_DEATH and friends to accept a matcher argument.\n\n\n#include \n\nnamespace testing {\n\n// Constructs a matcher that matches a const std::string& whose value is\n// equal to s.\nMatcher::Matcher(const std::string& s) { *this = Eq(s); }\n\n// Constructs a matcher that matches a const std::string& whose value is\n// equal to s.\nMatcher::Matcher(const char* s) {\n *this = Eq(std::string(s));\n}\n\n// Constructs a matcher that matches a std::string whose value is equal to\n// s.\nMatcher::Matcher(const std::string& s) { *this = Eq(s); }\n\n// Constructs a matcher that matches a std::string whose value is equal to\n// s.\nMatcher::Matcher(const char* s) { *this = Eq(std::string(s)); }\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n// Constructs a matcher that matches a const StringView& whose value is\n// equal to s.\nMatcher::Matcher(const std::string& s) {\n *this = Eq(s);\n}\n\n// Constructs a matcher that matches a const StringView& whose value is\n// equal to s.\nMatcher::Matcher(const char* s) {\n *this = Eq(std::string(s));\n}\n\n// Constructs a matcher that matches a const StringView& whose value is\n// equal to s.\nMatcher::Matcher(internal::StringView s) {\n *this = Eq(std::string(s));\n}\n\n// Constructs a matcher that matches a StringView whose value is equal to\n// s.\nMatcher::Matcher(const std::string& s) { *this = Eq(s); }\n\n// Constructs a matcher that matches a StringView whose value is equal to\n// s.\nMatcher::Matcher(const char* s) {\n *this = Eq(std::string(s));\n}\n\n// Constructs a matcher that matches a StringView whose value is equal to\n// s.\nMatcher::Matcher(internal::StringView s) {\n *this = Eq(std::string(s));\n}\n#endif // GTEST_INTERNAL_HAS_STRING_VIEW\n\n} // namespace testing\n// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if GTEST_OS_WINDOWS\n# include \n# include \n# include \n# include // Used in ThreadLocal.\n# ifdef _MSC_VER\n# include \n# endif // _MSC_VER\n#else\n# include \n#endif // GTEST_OS_WINDOWS\n\n#if GTEST_OS_MAC\n# include \n# include \n# include \n#endif // GTEST_OS_MAC\n\n#if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \\\n GTEST_OS_NETBSD || GTEST_OS_OPENBSD\n# include \n# if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD\n# include \n# endif\n#endif\n\n#if GTEST_OS_QNX\n# include \n# include \n# include \n#endif // GTEST_OS_QNX\n\n#if GTEST_OS_AIX\n# include \n# include \n#endif // GTEST_OS_AIX\n\n#if GTEST_OS_FUCHSIA\n# include \n# include \n#endif // GTEST_OS_FUCHSIA\n\n\nnamespace testing {\nnamespace internal {\n\n#if defined(_MSC_VER) || defined(__BORLANDC__)\n// MSVC and C++Builder do not provide a definition of STDERR_FILENO.\nconst int kStdOutFileno = 1;\nconst int kStdErrFileno = 2;\n#else\nconst int kStdOutFileno = STDOUT_FILENO;\nconst int kStdErrFileno = STDERR_FILENO;\n#endif // _MSC_VER\n\n#if GTEST_OS_LINUX\n\nnamespace {\ntemplate \nT ReadProcFileField(const std::string& filename, int field) {\n std::string dummy;\n std::ifstream file(filename.c_str());\n while (field-- > 0) {\n file >> dummy;\n }\n T output = 0;\n file >> output;\n return output;\n}\n} // namespace\n\n// Returns the number of active threads, or 0 when there is an error.\nsize_t GetThreadCount() {\n const std::string filename =\n (Message() << \"/proc/\" << getpid() << \"/stat\").GetString();\n return ReadProcFileField(filename, 19);\n}\n\n#elif GTEST_OS_MAC\n\nsize_t GetThreadCount() {\n const task_t task = mach_task_self();\n mach_msg_type_number_t thread_count;\n thread_act_array_t thread_list;\n const kern_return_t status = task_threads(task, &thread_list, &thread_count);\n if (status == KERN_SUCCESS) {\n // task_threads allocates resources in thread_list and we need to free them\n // to avoid leaks.\n vm_deallocate(task,\n reinterpret_cast(thread_list),\n sizeof(thread_t) * thread_count);\n return static_cast(thread_count);\n } else {\n return 0;\n }\n}\n\n#elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \\\n GTEST_OS_NETBSD\n\n#if GTEST_OS_NETBSD\n#undef KERN_PROC\n#define KERN_PROC KERN_PROC2\n#define kinfo_proc kinfo_proc2\n#endif\n\n#if GTEST_OS_DRAGONFLY\n#define KP_NLWP(kp) (kp.kp_nthreads)\n#elif GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD\n#define KP_NLWP(kp) (kp.ki_numthreads)\n#elif GTEST_OS_NETBSD\n#define KP_NLWP(kp) (kp.p_nlwps)\n#endif\n\n// Returns the number of threads running in the process, or 0 to indicate that\n// we cannot detect it.\nsize_t GetThreadCount() {\n int mib[] = {\n CTL_KERN,\n KERN_PROC,\n KERN_PROC_PID,\n getpid(),\n#if GTEST_OS_NETBSD\n sizeof(struct kinfo_proc),\n 1,\n#endif\n };\n u_int miblen = sizeof(mib) / sizeof(mib[0]);\n struct kinfo_proc info;\n size_t size = sizeof(info);\n if (sysctl(mib, miblen, &info, &size, NULL, 0)) {\n return 0;\n }\n return static_cast(KP_NLWP(info));\n}\n#elif GTEST_OS_OPENBSD\n\n// Returns the number of threads running in the process, or 0 to indicate that\n// we cannot detect it.\nsize_t GetThreadCount() {\n int mib[] = {\n CTL_KERN,\n KERN_PROC,\n KERN_PROC_PID | KERN_PROC_SHOW_THREADS,\n getpid(),\n sizeof(struct kinfo_proc),\n 0,\n };\n u_int miblen = sizeof(mib) / sizeof(mib[0]);\n\n // get number of structs\n size_t size;\n if (sysctl(mib, miblen, NULL, &size, NULL, 0)) {\n return 0;\n }\n\n mib[5] = static_cast(size / static_cast(mib[4]));\n\n // populate array of structs\n struct kinfo_proc info[mib[5]];\n if (sysctl(mib, miblen, &info, &size, NULL, 0)) {\n return 0;\n }\n\n // exclude empty members\n size_t nthreads = 0;\n for (size_t i = 0; i < size / static_cast(mib[4]); i++) {\n if (info[i].p_tid != -1)\n nthreads++;\n }\n return nthreads;\n}\n\n#elif GTEST_OS_QNX\n\n// Returns the number of threads running in the process, or 0 to indicate that\n// we cannot detect it.\nsize_t GetThreadCount() {\n const int fd = open(\"/proc/self/as\", O_RDONLY);\n if (fd < 0) {\n return 0;\n }\n procfs_info process_info;\n const int status =\n devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), nullptr);\n close(fd);\n if (status == EOK) {\n return static_cast(process_info.num_threads);\n } else {\n return 0;\n }\n}\n\n#elif GTEST_OS_AIX\n\nsize_t GetThreadCount() {\n struct procentry64 entry;\n pid_t pid = getpid();\n int status = getprocs64(&entry, sizeof(entry), nullptr, 0, &pid, 1);\n if (status == 1) {\n return entry.pi_thcount;\n } else {\n return 0;\n }\n}\n\n#elif GTEST_OS_FUCHSIA\n\nsize_t GetThreadCount() {\n int dummy_buffer;\n size_t avail;\n zx_status_t status = zx_object_get_info(\n zx_process_self(),\n ZX_INFO_PROCESS_THREADS,\n &dummy_buffer,\n 0,\n nullptr,\n &avail);\n if (status == ZX_OK) {\n return avail;\n } else {\n return 0;\n }\n}\n\n#else\n\nsize_t GetThreadCount() {\n // There's no portable way to detect the number of threads, so we just\n // return 0 to indicate that we cannot detect it.\n return 0;\n}\n\n#endif // GTEST_OS_LINUX\n\n#if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS\n\nvoid SleepMilliseconds(int n) {\n ::Sleep(static_cast(n));\n}\n\nAutoHandle::AutoHandle()\n : handle_(INVALID_HANDLE_VALUE) {}\n\nAutoHandle::AutoHandle(Handle handle)\n : handle_(handle) {}\n\nAutoHandle::~AutoHandle() {\n Reset();\n}\n\nAutoHandle::Handle AutoHandle::Get() const {\n return handle_;\n}\n\nvoid AutoHandle::Reset() {\n Reset(INVALID_HANDLE_VALUE);\n}\n\nvoid AutoHandle::Reset(HANDLE handle) {\n // Resetting with the same handle we already own is invalid.\n if (handle_ != handle) {\n if (IsCloseable()) {\n ::CloseHandle(handle_);\n }\n handle_ = handle;\n } else {\n GTEST_CHECK_(!IsCloseable())\n << \"Resetting a valid handle to itself is likely a programmer error \"\n \"and thus not allowed.\";\n }\n}\n\nbool AutoHandle::IsCloseable() const {\n // Different Windows APIs may use either of these values to represent an\n // invalid handle.\n return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE;\n}\n\nNotification::Notification()\n : event_(::CreateEvent(nullptr, // Default security attributes.\n TRUE, // Do not reset automatically.\n FALSE, // Initially unset.\n nullptr)) { // Anonymous event.\n GTEST_CHECK_(event_.Get() != nullptr);\n}\n\nvoid Notification::Notify() {\n GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);\n}\n\nvoid Notification::WaitForNotification() {\n GTEST_CHECK_(\n ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);\n}\n\nMutex::Mutex()\n : owner_thread_id_(0),\n type_(kDynamic),\n critical_section_init_phase_(0),\n critical_section_(new CRITICAL_SECTION) {\n ::InitializeCriticalSection(critical_section_);\n}\n\nMutex::~Mutex() {\n // Static mutexes are leaked intentionally. It is not thread-safe to try\n // to clean them up.\n if (type_ == kDynamic) {\n ::DeleteCriticalSection(critical_section_);\n delete critical_section_;\n critical_section_ = nullptr;\n }\n}\n\nvoid Mutex::Lock() {\n ThreadSafeLazyInit();\n ::EnterCriticalSection(critical_section_);\n owner_thread_id_ = ::GetCurrentThreadId();\n}\n\nvoid Mutex::Unlock() {\n ThreadSafeLazyInit();\n // We don't protect writing to owner_thread_id_ here, as it's the\n // caller's responsibility to ensure that the current thread holds the\n // mutex when this is called.\n owner_thread_id_ = 0;\n ::LeaveCriticalSection(critical_section_);\n}\n\n// Does nothing if the current thread holds the mutex. Otherwise, crashes\n// with high probability.\nvoid Mutex::AssertHeld() {\n ThreadSafeLazyInit();\n GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())\n << \"The current thread is not holding the mutex @\" << this;\n}\n\nnamespace {\n\n#ifdef _MSC_VER\n// Use the RAII idiom to flag mem allocs that are intentionally never\n// deallocated. The motivation is to silence the false positive mem leaks\n// that are reported by the debug version of MS's CRT which can only detect\n// if an alloc is missing a matching deallocation.\n// Example:\n// MemoryIsNotDeallocated memory_is_not_deallocated;\n// critical_section_ = new CRITICAL_SECTION;\n//\nclass MemoryIsNotDeallocated\n{\n public:\n MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {\n old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);\n // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT\n // doesn't report mem leak if there's no matching deallocation.\n _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);\n }\n\n ~MemoryIsNotDeallocated() {\n // Restore the original _CRTDBG_ALLOC_MEM_DF flag\n _CrtSetDbgFlag(old_crtdbg_flag_);\n }\n\n private:\n int old_crtdbg_flag_;\n\n GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated);\n};\n#endif // _MSC_VER\n\n} // namespace\n\n// Initializes owner_thread_id_ and critical_section_ in static mutexes.\nvoid Mutex::ThreadSafeLazyInit() {\n // Dynamic mutexes are initialized in the constructor.\n if (type_ == kStatic) {\n switch (\n ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {\n case 0:\n // If critical_section_init_phase_ was 0 before the exchange, we\n // are the first to test it and need to perform the initialization.\n owner_thread_id_ = 0;\n {\n // Use RAII to flag that following mem alloc is never deallocated.\n#ifdef _MSC_VER\n MemoryIsNotDeallocated memory_is_not_deallocated;\n#endif // _MSC_VER\n critical_section_ = new CRITICAL_SECTION;\n }\n ::InitializeCriticalSection(critical_section_);\n // Updates the critical_section_init_phase_ to 2 to signal\n // initialization complete.\n GTEST_CHECK_(::InterlockedCompareExchange(\n &critical_section_init_phase_, 2L, 1L) ==\n 1L);\n break;\n case 1:\n // Somebody else is already initializing the mutex; spin until they\n // are done.\n while (::InterlockedCompareExchange(&critical_section_init_phase_,\n 2L,\n 2L) != 2L) {\n // Possibly yields the rest of the thread's time slice to other\n // threads.\n ::Sleep(0);\n }\n break;\n\n case 2:\n break; // The mutex is already initialized and ready for use.\n\n default:\n GTEST_CHECK_(false)\n << \"Unexpected value of critical_section_init_phase_ \"\n << \"while initializing a static mutex.\";\n }\n }\n}\n\nnamespace {\n\nclass ThreadWithParamSupport : public ThreadWithParamBase {\n public:\n static HANDLE CreateThread(Runnable* runnable,\n Notification* thread_can_start) {\n ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);\n DWORD thread_id;\n HANDLE thread_handle = ::CreateThread(\n nullptr, // Default security.\n 0, // Default stack size.\n &ThreadWithParamSupport::ThreadMain,\n param, // Parameter to ThreadMainStatic\n 0x0, // Default creation flags.\n &thread_id); // Need a valid pointer for the call to work under Win98.\n GTEST_CHECK_(thread_handle != nullptr)\n << \"CreateThread failed with error \" << ::GetLastError() << \".\";\n if (thread_handle == nullptr) {\n delete param;\n }\n return thread_handle;\n }\n\n private:\n struct ThreadMainParam {\n ThreadMainParam(Runnable* runnable, Notification* thread_can_start)\n : runnable_(runnable),\n thread_can_start_(thread_can_start) {\n }\n std::unique_ptr runnable_;\n // Does not own.\n Notification* thread_can_start_;\n };\n\n static DWORD WINAPI ThreadMain(void* ptr) {\n // Transfers ownership.\n std::unique_ptr param(static_cast(ptr));\n if (param->thread_can_start_ != nullptr)\n param->thread_can_start_->WaitForNotification();\n param->runnable_->Run();\n return 0;\n }\n\n // Prohibit instantiation.\n ThreadWithParamSupport();\n\n GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);\n};\n\n} // namespace\n\nThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,\n Notification* thread_can_start)\n : thread_(ThreadWithParamSupport::CreateThread(runnable,\n thread_can_start)) {\n}\n\nThreadWithParamBase::~ThreadWithParamBase() {\n Join();\n}\n\nvoid ThreadWithParamBase::Join() {\n GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)\n << \"Failed to join the thread with error \" << ::GetLastError() << \".\";\n}\n\n// Maps a thread to a set of ThreadIdToThreadLocals that have values\n// instantiated on that thread and notifies them when the thread exits. A\n// ThreadLocal instance is expected to persist until all threads it has\n// values on have terminated.\nclass ThreadLocalRegistryImpl {\n public:\n // Registers thread_local_instance as having value on the current thread.\n // Returns a value that can be used to identify the thread from other threads.\n static ThreadLocalValueHolderBase* GetValueOnCurrentThread(\n const ThreadLocalBase* thread_local_instance) {\n#ifdef _MSC_VER\n MemoryIsNotDeallocated memory_is_not_deallocated;\n#endif // _MSC_VER\n DWORD current_thread = ::GetCurrentThreadId();\n MutexLock lock(&mutex_);\n ThreadIdToThreadLocals* const thread_to_thread_locals =\n GetThreadLocalsMapLocked();\n ThreadIdToThreadLocals::iterator thread_local_pos =\n thread_to_thread_locals->find(current_thread);\n if (thread_local_pos == thread_to_thread_locals->end()) {\n thread_local_pos = thread_to_thread_locals->insert(\n std::make_pair(current_thread, ThreadLocalValues())).first;\n StartWatcherThreadFor(current_thread);\n }\n ThreadLocalValues& thread_local_values = thread_local_pos->second;\n ThreadLocalValues::iterator value_pos =\n thread_local_values.find(thread_local_instance);\n if (value_pos == thread_local_values.end()) {\n value_pos =\n thread_local_values\n .insert(std::make_pair(\n thread_local_instance,\n std::shared_ptr(\n thread_local_instance->NewValueForCurrentThread())))\n .first;\n }\n return value_pos->second.get();\n }\n\n static void OnThreadLocalDestroyed(\n const ThreadLocalBase* thread_local_instance) {\n std::vector > value_holders;\n // Clean up the ThreadLocalValues data structure while holding the lock, but\n // defer the destruction of the ThreadLocalValueHolderBases.\n {\n MutexLock lock(&mutex_);\n ThreadIdToThreadLocals* const thread_to_thread_locals =\n GetThreadLocalsMapLocked();\n for (ThreadIdToThreadLocals::iterator it =\n thread_to_thread_locals->begin();\n it != thread_to_thread_locals->end();\n ++it) {\n ThreadLocalValues& thread_local_values = it->second;\n ThreadLocalValues::iterator value_pos =\n thread_local_values.find(thread_local_instance);\n if (value_pos != thread_local_values.end()) {\n value_holders.push_back(value_pos->second);\n thread_local_values.erase(value_pos);\n // This 'if' can only be successful at most once, so theoretically we\n // could break out of the loop here, but we don't bother doing so.\n }\n }\n }\n // Outside the lock, let the destructor for 'value_holders' deallocate the\n // ThreadLocalValueHolderBases.\n }\n\n static void OnThreadExit(DWORD thread_id) {\n GTEST_CHECK_(thread_id != 0) << ::GetLastError();\n std::vector > value_holders;\n // Clean up the ThreadIdToThreadLocals data structure while holding the\n // lock, but defer the destruction of the ThreadLocalValueHolderBases.\n {\n MutexLock lock(&mutex_);\n ThreadIdToThreadLocals* const thread_to_thread_locals =\n GetThreadLocalsMapLocked();\n ThreadIdToThreadLocals::iterator thread_local_pos =\n thread_to_thread_locals->find(thread_id);\n if (thread_local_pos != thread_to_thread_locals->end()) {\n ThreadLocalValues& thread_local_values = thread_local_pos->second;\n for (ThreadLocalValues::iterator value_pos =\n thread_local_values.begin();\n value_pos != thread_local_values.end();\n ++value_pos) {\n value_holders.push_back(value_pos->second);\n }\n thread_to_thread_locals->erase(thread_local_pos);\n }\n }\n // Outside the lock, let the destructor for 'value_holders' deallocate the\n // ThreadLocalValueHolderBases.\n }\n\n private:\n // In a particular thread, maps a ThreadLocal object to its value.\n typedef std::map >\n ThreadLocalValues;\n // Stores all ThreadIdToThreadLocals having values in a thread, indexed by\n // thread's ID.\n typedef std::map ThreadIdToThreadLocals;\n\n // Holds the thread id and thread handle that we pass from\n // StartWatcherThreadFor to WatcherThreadFunc.\n typedef std::pair ThreadIdAndHandle;\n\n static void StartWatcherThreadFor(DWORD thread_id) {\n // The returned handle will be kept in thread_map and closed by\n // watcher_thread in WatcherThreadFunc.\n HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,\n FALSE,\n thread_id);\n GTEST_CHECK_(thread != nullptr);\n // We need to pass a valid thread ID pointer into CreateThread for it\n // to work correctly under Win98.\n DWORD watcher_thread_id;\n HANDLE watcher_thread = ::CreateThread(\n nullptr, // Default security.\n 0, // Default stack size\n &ThreadLocalRegistryImpl::WatcherThreadFunc,\n reinterpret_cast(new ThreadIdAndHandle(thread_id, thread)),\n CREATE_SUSPENDED, &watcher_thread_id);\n GTEST_CHECK_(watcher_thread != nullptr);\n // Give the watcher thread the same priority as ours to avoid being\n // blocked by it.\n ::SetThreadPriority(watcher_thread,\n ::GetThreadPriority(::GetCurrentThread()));\n ::ResumeThread(watcher_thread);\n ::CloseHandle(watcher_thread);\n }\n\n // Monitors exit from a given thread and notifies those\n // ThreadIdToThreadLocals about thread termination.\n static DWORD WINAPI WatcherThreadFunc(LPVOID param) {\n const ThreadIdAndHandle* tah =\n reinterpret_cast(param);\n GTEST_CHECK_(\n ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);\n OnThreadExit(tah->first);\n ::CloseHandle(tah->second);\n delete tah;\n return 0;\n }\n\n // Returns map of thread local instances.\n static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {\n mutex_.AssertHeld();\n#ifdef _MSC_VER\n MemoryIsNotDeallocated memory_is_not_deallocated;\n#endif // _MSC_VER\n static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals();\n return map;\n }\n\n // Protects access to GetThreadLocalsMapLocked() and its return value.\n static Mutex mutex_;\n // Protects access to GetThreadMapLocked() and its return value.\n static Mutex thread_map_mutex_;\n};\n\nMutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);\nMutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);\n\nThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(\n const ThreadLocalBase* thread_local_instance) {\n return ThreadLocalRegistryImpl::GetValueOnCurrentThread(\n thread_local_instance);\n}\n\nvoid ThreadLocalRegistry::OnThreadLocalDestroyed(\n const ThreadLocalBase* thread_local_instance) {\n ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);\n}\n\n#endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS\n\n#if GTEST_USES_POSIX_RE\n\n// Implements RE. Currently only needed for death tests.\n\nRE::~RE() {\n if (is_valid_) {\n // regfree'ing an invalid regex might crash because the content\n // of the regex is undefined. Since the regex's are essentially\n // the same, one cannot be valid (or invalid) without the other\n // being so too.\n regfree(&partial_regex_);\n regfree(&full_regex_);\n }\n free(const_cast(pattern_));\n}\n\n// Returns true if and only if regular expression re matches the entire str.\nbool RE::FullMatch(const char* str, const RE& re) {\n if (!re.is_valid_) return false;\n\n regmatch_t match;\n return regexec(&re.full_regex_, str, 1, &match, 0) == 0;\n}\n\n// Returns true if and only if regular expression re matches a substring of\n// str (including str itself).\nbool RE::PartialMatch(const char* str, const RE& re) {\n if (!re.is_valid_) return false;\n\n regmatch_t match;\n return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;\n}\n\n// Initializes an RE from its string representation.\nvoid RE::Init(const char* regex) {\n pattern_ = posix::StrDup(regex);\n\n // Reserves enough bytes to hold the regular expression used for a\n // full match.\n const size_t full_regex_len = strlen(regex) + 10;\n char* const full_pattern = new char[full_regex_len];\n\n snprintf(full_pattern, full_regex_len, \"^(%s)$\", regex);\n is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;\n // We want to call regcomp(&partial_regex_, ...) even if the\n // previous expression returns false. Otherwise partial_regex_ may\n // not be properly initialized can may cause trouble when it's\n // freed.\n //\n // Some implementation of POSIX regex (e.g. on at least some\n // versions of Cygwin) doesn't accept the empty string as a valid\n // regex. We change it to an equivalent form \"()\" to be safe.\n if (is_valid_) {\n const char* const partial_regex = (*regex == '\\0') ? \"()\" : regex;\n is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;\n }\n EXPECT_TRUE(is_valid_)\n << \"Regular expression \\\"\" << regex\n << \"\\\" is not a valid POSIX Extended regular expression.\";\n\n delete[] full_pattern;\n}\n\n#elif GTEST_USES_SIMPLE_RE\n\n// Returns true if and only if ch appears anywhere in str (excluding the\n// terminating '\\0' character).\nbool IsInSet(char ch, const char* str) {\n return ch != '\\0' && strchr(str, ch) != nullptr;\n}\n\n// Returns true if and only if ch belongs to the given classification.\n// Unlike similar functions in , these aren't affected by the\n// current locale.\nbool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }\nbool IsAsciiPunct(char ch) {\n return IsInSet(ch, \"^-!\\\"#$%&'()*+,./:;<=>?@[\\\\]_`{|}~\");\n}\nbool IsRepeat(char ch) { return IsInSet(ch, \"?*+\"); }\nbool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, \" \\f\\n\\r\\t\\v\"); }\nbool IsAsciiWordChar(char ch) {\n return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||\n ('0' <= ch && ch <= '9') || ch == '_';\n}\n\n// Returns true if and only if \"\\\\c\" is a supported escape sequence.\nbool IsValidEscape(char c) {\n return (IsAsciiPunct(c) || IsInSet(c, \"dDfnrsStvwW\"));\n}\n\n// Returns true if and only if the given atom (specified by escaped and\n// pattern) matches ch. The result is undefined if the atom is invalid.\nbool AtomMatchesChar(bool escaped, char pattern_char, char ch) {\n if (escaped) { // \"\\\\p\" where p is pattern_char.\n switch (pattern_char) {\n case 'd': return IsAsciiDigit(ch);\n case 'D': return !IsAsciiDigit(ch);\n case 'f': return ch == '\\f';\n case 'n': return ch == '\\n';\n case 'r': return ch == '\\r';\n case 's': return IsAsciiWhiteSpace(ch);\n case 'S': return !IsAsciiWhiteSpace(ch);\n case 't': return ch == '\\t';\n case 'v': return ch == '\\v';\n case 'w': return IsAsciiWordChar(ch);\n case 'W': return !IsAsciiWordChar(ch);\n }\n return IsAsciiPunct(pattern_char) && pattern_char == ch;\n }\n\n return (pattern_char == '.' && ch != '\\n') || pattern_char == ch;\n}\n\n// Helper function used by ValidateRegex() to format error messages.\nstatic std::string FormatRegexSyntaxError(const char* regex, int index) {\n return (Message() << \"Syntax error at index \" << index\n << \" in simple regular expression \\\"\" << regex << \"\\\": \").GetString();\n}\n\n// Generates non-fatal failures and returns false if regex is invalid;\n// otherwise returns true.\nbool ValidateRegex(const char* regex) {\n if (regex == nullptr) {\n ADD_FAILURE() << \"NULL is not a valid simple regular expression.\";\n return false;\n }\n\n bool is_valid = true;\n\n // True if and only if ?, *, or + can follow the previous atom.\n bool prev_repeatable = false;\n for (int i = 0; regex[i]; i++) {\n if (regex[i] == '\\\\') { // An escape sequence\n i++;\n if (regex[i] == '\\0') {\n ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)\n << \"'\\\\' cannot appear at the end.\";\n return false;\n }\n\n if (!IsValidEscape(regex[i])) {\n ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)\n << \"invalid escape sequence \\\"\\\\\" << regex[i] << \"\\\".\";\n is_valid = false;\n }\n prev_repeatable = true;\n } else { // Not an escape sequence.\n const char ch = regex[i];\n\n if (ch == '^' && i > 0) {\n ADD_FAILURE() << FormatRegexSyntaxError(regex, i)\n << \"'^' can only appear at the beginning.\";\n is_valid = false;\n } else if (ch == '$' && regex[i + 1] != '\\0') {\n ADD_FAILURE() << FormatRegexSyntaxError(regex, i)\n << \"'$' can only appear at the end.\";\n is_valid = false;\n } else if (IsInSet(ch, \"()[]{}|\")) {\n ADD_FAILURE() << FormatRegexSyntaxError(regex, i)\n << \"'\" << ch << \"' is unsupported.\";\n is_valid = false;\n } else if (IsRepeat(ch) && !prev_repeatable) {\n ADD_FAILURE() << FormatRegexSyntaxError(regex, i)\n << \"'\" << ch << \"' can only follow a repeatable token.\";\n is_valid = false;\n }\n\n prev_repeatable = !IsInSet(ch, \"^$?*+\");\n }\n }\n\n return is_valid;\n}\n\n// Matches a repeated regex atom followed by a valid simple regular\n// expression. The regex atom is defined as c if escaped is false,\n// or \\c otherwise. repeat is the repetition meta character (?, *,\n// or +). The behavior is undefined if str contains too many\n// characters to be indexable by size_t, in which case the test will\n// probably time out anyway. We are fine with this limitation as\n// std::string has it too.\nbool MatchRepetitionAndRegexAtHead(\n bool escaped, char c, char repeat, const char* regex,\n const char* str) {\n const size_t min_count = (repeat == '+') ? 1 : 0;\n const size_t max_count = (repeat == '?') ? 1 :\n static_cast(-1) - 1;\n // We cannot call numeric_limits::max() as it conflicts with the\n // max() macro on Windows.\n\n for (size_t i = 0; i <= max_count; ++i) {\n // We know that the atom matches each of the first i characters in str.\n if (i >= min_count && MatchRegexAtHead(regex, str + i)) {\n // We have enough matches at the head, and the tail matches too.\n // Since we only care about *whether* the pattern matches str\n // (as opposed to *how* it matches), there is no need to find a\n // greedy match.\n return true;\n }\n if (str[i] == '\\0' || !AtomMatchesChar(escaped, c, str[i]))\n return false;\n }\n return false;\n}\n\n// Returns true if and only if regex matches a prefix of str. regex must\n// be a valid simple regular expression and not start with \"^\", or the\n// result is undefined.\nbool MatchRegexAtHead(const char* regex, const char* str) {\n if (*regex == '\\0') // An empty regex matches a prefix of anything.\n return true;\n\n // \"$\" only matches the end of a string. Note that regex being\n // valid guarantees that there's nothing after \"$\" in it.\n if (*regex == '$')\n return *str == '\\0';\n\n // Is the first thing in regex an escape sequence?\n const bool escaped = *regex == '\\\\';\n if (escaped)\n ++regex;\n if (IsRepeat(regex[1])) {\n // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so\n // here's an indirect recursion. It terminates as the regex gets\n // shorter in each recursion.\n return MatchRepetitionAndRegexAtHead(\n escaped, regex[0], regex[1], regex + 2, str);\n } else {\n // regex isn't empty, isn't \"$\", and doesn't start with a\n // repetition. We match the first atom of regex with the first\n // character of str and recurse.\n return (*str != '\\0') && AtomMatchesChar(escaped, *regex, *str) &&\n MatchRegexAtHead(regex + 1, str + 1);\n }\n}\n\n// Returns true if and only if regex matches any substring of str. regex must\n// be a valid simple regular expression, or the result is undefined.\n//\n// The algorithm is recursive, but the recursion depth doesn't exceed\n// the regex length, so we won't need to worry about running out of\n// stack space normally. In rare cases the time complexity can be\n// exponential with respect to the regex length + the string length,\n// but usually it's must faster (often close to linear).\nbool MatchRegexAnywhere(const char* regex, const char* str) {\n if (regex == nullptr || str == nullptr) return false;\n\n if (*regex == '^')\n return MatchRegexAtHead(regex + 1, str);\n\n // A successful match can be anywhere in str.\n do {\n if (MatchRegexAtHead(regex, str))\n return true;\n } while (*str++ != '\\0');\n return false;\n}\n\n// Implements the RE class.\n\nRE::~RE() {\n free(const_cast(pattern_));\n free(const_cast(full_pattern_));\n}\n\n// Returns true if and only if regular expression re matches the entire str.\nbool RE::FullMatch(const char* str, const RE& re) {\n return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);\n}\n\n// Returns true if and only if regular expression re matches a substring of\n// str (including str itself).\nbool RE::PartialMatch(const char* str, const RE& re) {\n return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);\n}\n\n// Initializes an RE from its string representation.\nvoid RE::Init(const char* regex) {\n pattern_ = full_pattern_ = nullptr;\n if (regex != nullptr) {\n pattern_ = posix::StrDup(regex);\n }\n\n is_valid_ = ValidateRegex(regex);\n if (!is_valid_) {\n // No need to calculate the full pattern when the regex is invalid.\n return;\n }\n\n const size_t len = strlen(regex);\n // Reserves enough bytes to hold the regular expression used for a\n // full match: we need space to prepend a '^', append a '$', and\n // terminate the string with '\\0'.\n char* buffer = static_cast(malloc(len + 3));\n full_pattern_ = buffer;\n\n if (*regex != '^')\n *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.\n\n // We don't use snprintf or strncpy, as they trigger a warning when\n // compiled with VC++ 8.0.\n memcpy(buffer, regex, len);\n buffer += len;\n\n if (len == 0 || regex[len - 1] != '$')\n *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.\n\n *buffer = '\\0';\n}\n\n#endif // GTEST_USES_POSIX_RE\n\nconst char kUnknownFile[] = \"unknown file\";\n\n// Formats a source file path and a line number as they would appear\n// in an error message from the compiler used to compile this code.\nGTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {\n const std::string file_name(file == nullptr ? kUnknownFile : file);\n\n if (line < 0) {\n return file_name + \":\";\n }\n#ifdef _MSC_VER\n return file_name + \"(\" + StreamableToString(line) + \"):\";\n#else\n return file_name + \":\" + StreamableToString(line) + \":\";\n#endif // _MSC_VER\n}\n\n// Formats a file location for compiler-independent XML output.\n// Although this function is not platform dependent, we put it next to\n// FormatFileLocation in order to contrast the two functions.\n// Note that FormatCompilerIndependentFileLocation() does NOT append colon\n// to the file location it produces, unlike FormatFileLocation().\nGTEST_API_ ::std::string FormatCompilerIndependentFileLocation(\n const char* file, int line) {\n const std::string file_name(file == nullptr ? kUnknownFile : file);\n\n if (line < 0)\n return file_name;\n else\n return file_name + \":\" + StreamableToString(line);\n}\n\nGTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)\n : severity_(severity) {\n const char* const marker =\n severity == GTEST_INFO ? \"[ INFO ]\" :\n severity == GTEST_WARNING ? \"[WARNING]\" :\n severity == GTEST_ERROR ? \"[ ERROR ]\" : \"[ FATAL ]\";\n GetStream() << ::std::endl << marker << \" \"\n << FormatFileLocation(file, line).c_str() << \": \";\n}\n\n// Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.\nGTestLog::~GTestLog() {\n GetStream() << ::std::endl;\n if (severity_ == GTEST_FATAL) {\n fflush(stderr);\n posix::Abort();\n }\n}\n\n// Disable Microsoft deprecation warnings for POSIX functions called from\n// this class (creat, dup, dup2, and close)\nGTEST_DISABLE_MSC_DEPRECATED_PUSH_()\n\n#if GTEST_HAS_STREAM_REDIRECTION\n\n// Object that captures an output stream (stdout/stderr).\nclass CapturedStream {\n public:\n // The ctor redirects the stream to a temporary file.\n explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {\n# if GTEST_OS_WINDOWS\n char temp_dir_path[MAX_PATH + 1] = { '\\0' }; // NOLINT\n char temp_file_path[MAX_PATH + 1] = { '\\0' }; // NOLINT\n\n ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);\n const UINT success = ::GetTempFileNameA(temp_dir_path,\n \"gtest_redir\",\n 0, // Generate unique file name.\n temp_file_path);\n GTEST_CHECK_(success != 0)\n << \"Unable to create a temporary file in \" << temp_dir_path;\n const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);\n GTEST_CHECK_(captured_fd != -1) << \"Unable to open temporary file \"\n << temp_file_path;\n filename_ = temp_file_path;\n# else\n // There's no guarantee that a test has write access to the current\n // directory, so we create the temporary file in the /tmp directory\n // instead. We use /tmp on most systems, and /sdcard on Android.\n // That's because Android doesn't have /tmp.\n# if GTEST_OS_LINUX_ANDROID\n // Note: Android applications are expected to call the framework's\n // Context.getExternalStorageDirectory() method through JNI to get\n // the location of the world-writable SD Card directory. However,\n // this requires a Context handle, which cannot be retrieved\n // globally from native code. Doing so also precludes running the\n // code as part of a regular standalone executable, which doesn't\n // run in a Dalvik process (e.g. when running it through 'adb shell').\n //\n // The location /data/local/tmp is directly accessible from native code.\n // '/sdcard' and other variants cannot be relied on, as they are not\n // guaranteed to be mounted, or may have a delay in mounting.\n char name_template[] = \"/data/local/tmp/gtest_captured_stream.XXXXXX\";\n# else\n char name_template[] = \"/tmp/captured_stream.XXXXXX\";\n# endif // GTEST_OS_LINUX_ANDROID\n const int captured_fd = mkstemp(name_template);\n if (captured_fd == -1) {\n GTEST_LOG_(WARNING)\n << \"Failed to create tmp file \" << name_template\n << \" for test; does the test have access to the /tmp directory?\";\n }\n filename_ = name_template;\n# endif // GTEST_OS_WINDOWS\n fflush(nullptr);\n dup2(captured_fd, fd_);\n close(captured_fd);\n }\n\n ~CapturedStream() {\n remove(filename_.c_str());\n }\n\n std::string GetCapturedString() {\n if (uncaptured_fd_ != -1) {\n // Restores the original stream.\n fflush(nullptr);\n dup2(uncaptured_fd_, fd_);\n close(uncaptured_fd_);\n uncaptured_fd_ = -1;\n }\n\n FILE* const file = posix::FOpen(filename_.c_str(), \"r\");\n if (file == nullptr) {\n GTEST_LOG_(FATAL) << \"Failed to open tmp file \" << filename_\n << \" for capturing stream.\";\n }\n const std::string content = ReadEntireFile(file);\n posix::FClose(file);\n return content;\n }\n\n private:\n const int fd_; // A stream to capture.\n int uncaptured_fd_;\n // Name of the temporary file holding the stderr output.\n ::std::string filename_;\n\n GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);\n};\n\nGTEST_DISABLE_MSC_DEPRECATED_POP_()\n\nstatic CapturedStream* g_captured_stderr = nullptr;\nstatic CapturedStream* g_captured_stdout = nullptr;\n\n// Starts capturing an output stream (stdout/stderr).\nstatic void CaptureStream(int fd, const char* stream_name,\n CapturedStream** stream) {\n if (*stream != nullptr) {\n GTEST_LOG_(FATAL) << \"Only one \" << stream_name\n << \" capturer can exist at a time.\";\n }\n *stream = new CapturedStream(fd);\n}\n\n// Stops capturing the output stream and returns the captured string.\nstatic std::string GetCapturedStream(CapturedStream** captured_stream) {\n const std::string content = (*captured_stream)->GetCapturedString();\n\n delete *captured_stream;\n *captured_stream = nullptr;\n\n return content;\n}\n\n// Starts capturing stdout.\nvoid CaptureStdout() {\n CaptureStream(kStdOutFileno, \"stdout\", &g_captured_stdout);\n}\n\n// Starts capturing stderr.\nvoid CaptureStderr() {\n CaptureStream(kStdErrFileno, \"stderr\", &g_captured_stderr);\n}\n\n// Stops capturing stdout and returns the captured string.\nstd::string GetCapturedStdout() {\n return GetCapturedStream(&g_captured_stdout);\n}\n\n// Stops capturing stderr and returns the captured string.\nstd::string GetCapturedStderr() {\n return GetCapturedStream(&g_captured_stderr);\n}\n\n#endif // GTEST_HAS_STREAM_REDIRECTION\n\n\n\n\n\nsize_t GetFileSize(FILE* file) {\n fseek(file, 0, SEEK_END);\n return static_cast(ftell(file));\n}\n\nstd::string ReadEntireFile(FILE* file) {\n const size_t file_size = GetFileSize(file);\n char* const buffer = new char[file_size];\n\n size_t bytes_last_read = 0; // # of bytes read in the last fread()\n size_t bytes_read = 0; // # of bytes read so far\n\n fseek(file, 0, SEEK_SET);\n\n // Keeps reading the file until we cannot read further or the\n // pre-determined file size is reached.\n do {\n bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);\n bytes_read += bytes_last_read;\n } while (bytes_last_read > 0 && bytes_read < file_size);\n\n const std::string content(buffer, bytes_read);\n delete[] buffer;\n\n return content;\n}\n\n#if GTEST_HAS_DEATH_TEST\nstatic const std::vector* g_injected_test_argvs =\n nullptr; // Owned.\n\nstd::vector GetInjectableArgvs() {\n if (g_injected_test_argvs != nullptr) {\n return *g_injected_test_argvs;\n }\n return GetArgvs();\n}\n\nvoid SetInjectableArgvs(const std::vector* new_argvs) {\n if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs;\n g_injected_test_argvs = new_argvs;\n}\n\nvoid SetInjectableArgvs(const std::vector& new_argvs) {\n SetInjectableArgvs(\n new std::vector(new_argvs.begin(), new_argvs.end()));\n}\n\nvoid ClearInjectableArgvs() {\n delete g_injected_test_argvs;\n g_injected_test_argvs = nullptr;\n}\n#endif // GTEST_HAS_DEATH_TEST\n\n#if GTEST_OS_WINDOWS_MOBILE\nnamespace posix {\nvoid Abort() {\n DebugBreak();\n TerminateProcess(GetCurrentProcess(), 1);\n}\n} // namespace posix\n#endif // GTEST_OS_WINDOWS_MOBILE\n\n// Returns the name of the environment variable corresponding to the\n// given flag. For example, FlagToEnvVar(\"foo\") will return\n// \"GTEST_FOO\" in the open-source version.\nstatic std::string FlagToEnvVar(const char* flag) {\n const std::string full_flag =\n (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();\n\n Message env_var;\n for (size_t i = 0; i != full_flag.length(); i++) {\n env_var << ToUpper(full_flag.c_str()[i]);\n }\n\n return env_var.GetString();\n}\n\n// Parses 'str' for a 32-bit signed integer. If successful, writes\n// the result to *value and returns true; otherwise leaves *value\n// unchanged and returns false.\nbool ParseInt32(const Message& src_text, const char* str, int32_t* value) {\n // Parses the environment variable as a decimal integer.\n char* end = nullptr;\n const long long_value = strtol(str, &end, 10); // NOLINT\n\n // Has strtol() consumed all characters in the string?\n if (*end != '\\0') {\n // No - an invalid character was encountered.\n Message msg;\n msg << \"WARNING: \" << src_text\n << \" is expected to be a 32-bit integer, but actually\"\n << \" has value \\\"\" << str << \"\\\".\\n\";\n printf(\"%s\", msg.GetString().c_str());\n fflush(stdout);\n return false;\n }\n\n // Is the parsed value in the range of an int32_t?\n const auto result = static_cast(long_value);\n if (long_value == LONG_MAX || long_value == LONG_MIN ||\n // The parsed value overflows as a long. (strtol() returns\n // LONG_MAX or LONG_MIN when the input overflows.)\n result != long_value\n // The parsed value overflows as an int32_t.\n ) {\n Message msg;\n msg << \"WARNING: \" << src_text\n << \" is expected to be a 32-bit integer, but actually\"\n << \" has value \" << str << \", which overflows.\\n\";\n printf(\"%s\", msg.GetString().c_str());\n fflush(stdout);\n return false;\n }\n\n *value = result;\n return true;\n}\n\n// Reads and returns the Boolean environment variable corresponding to\n// the given flag; if it's not set, returns default_value.\n//\n// The value is considered true if and only if it's not \"0\".\nbool BoolFromGTestEnv(const char* flag, bool default_value) {\n#if defined(GTEST_GET_BOOL_FROM_ENV_)\n return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);\n#else\n const std::string env_var = FlagToEnvVar(flag);\n const char* const string_value = posix::GetEnv(env_var.c_str());\n return string_value == nullptr ? default_value\n : strcmp(string_value, \"0\") != 0;\n#endif // defined(GTEST_GET_BOOL_FROM_ENV_)\n}\n\n// Reads and returns a 32-bit integer stored in the environment\n// variable corresponding to the given flag; if it isn't set or\n// doesn't represent a valid 32-bit integer, returns default_value.\nint32_t Int32FromGTestEnv(const char* flag, int32_t default_value) {\n#if defined(GTEST_GET_INT32_FROM_ENV_)\n return GTEST_GET_INT32_FROM_ENV_(flag, default_value);\n#else\n const std::string env_var = FlagToEnvVar(flag);\n const char* const string_value = posix::GetEnv(env_var.c_str());\n if (string_value == nullptr) {\n // The environment variable is not set.\n return default_value;\n }\n\n int32_t result = default_value;\n if (!ParseInt32(Message() << \"Environment variable \" << env_var,\n string_value, &result)) {\n printf(\"The default value %s is used.\\n\",\n (Message() << default_value).GetString().c_str());\n fflush(stdout);\n return default_value;\n }\n\n return result;\n#endif // defined(GTEST_GET_INT32_FROM_ENV_)\n}\n\n// As a special case for the 'output' flag, if GTEST_OUTPUT is not\n// set, we look for XML_OUTPUT_FILE, which is set by the Bazel build\n// system. The value of XML_OUTPUT_FILE is a filename without the\n// \"xml:\" prefix of GTEST_OUTPUT.\n// Note that this is meant to be called at the call site so it does\n// not check that the flag is 'output'\n// In essence this checks an env variable called XML_OUTPUT_FILE\n// and if it is set we prepend \"xml:\" to its value, if it not set we return \"\"\nstd::string OutputFlagAlsoCheckEnvVar(){\n std::string default_value_for_output_flag = \"\";\n const char* xml_output_file_env = posix::GetEnv(\"XML_OUTPUT_FILE\");\n if (nullptr != xml_output_file_env) {\n default_value_for_output_flag = std::string(\"xml:\") + xml_output_file_env;\n }\n return default_value_for_output_flag;\n}\n\n// Reads and returns the string environment variable corresponding to\n// the given flag; if it's not set, returns default_value.\nconst char* StringFromGTestEnv(const char* flag, const char* default_value) {\n#if defined(GTEST_GET_STRING_FROM_ENV_)\n return GTEST_GET_STRING_FROM_ENV_(flag, default_value);\n#else\n const std::string env_var = FlagToEnvVar(flag);\n const char* const value = posix::GetEnv(env_var.c_str());\n return value == nullptr ? default_value : value;\n#endif // defined(GTEST_GET_STRING_FROM_ENV_)\n}\n\n} // namespace internal\n} // namespace testing\n// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n// Google Test - The Google C++ Testing and Mocking Framework\n//\n// This file implements a universal value printer that can print a\n// value of any type T:\n//\n// void ::testing::internal::UniversalPrinter::Print(value, ostream_ptr);\n//\n// It uses the << operator when possible, and prints the bytes in the\n// object otherwise. A user can override its behavior for a class\n// type Foo by defining either operator<<(::std::ostream&, const Foo&)\n// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that\n// defines Foo.\n\n\n#include \n\n#include \n#include \n#include \n#include // NOLINT\n#include \n#include \n\n\nnamespace testing {\n\nnamespace {\n\nusing ::std::ostream;\n\n// Prints a segment of bytes in the given object.\nGTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_\nGTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_\nGTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_\nGTEST_ATTRIBUTE_NO_SANITIZE_THREAD_\nvoid PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,\n size_t count, ostream* os) {\n char text[5] = \"\";\n for (size_t i = 0; i != count; i++) {\n const size_t j = start + i;\n if (i != 0) {\n // Organizes the bytes into groups of 2 for easy parsing by\n // human.\n if ((j % 2) == 0)\n *os << ' ';\n else\n *os << '-';\n }\n GTEST_SNPRINTF_(text, sizeof(text), \"%02X\", obj_bytes[j]);\n *os << text;\n }\n}\n\n// Prints the bytes in the given value to the given ostream.\nvoid PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,\n ostream* os) {\n // Tells the user how big the object is.\n *os << count << \"-byte object <\";\n\n const size_t kThreshold = 132;\n const size_t kChunkSize = 64;\n // If the object size is bigger than kThreshold, we'll have to omit\n // some details by printing only the first and the last kChunkSize\n // bytes.\n if (count < kThreshold) {\n PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);\n } else {\n PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);\n *os << \" ... \";\n // Rounds up to 2-byte boundary.\n const size_t resume_pos = (count - kChunkSize + 1)/2*2;\n PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);\n }\n *os << \">\";\n}\n\n// Helpers for widening a character to char32_t. Since the standard does not\n// specify if char / wchar_t is signed or unsigned, it is important to first\n// convert it to the unsigned type of the same width before widening it to\n// char32_t.\ntemplate \nchar32_t ToChar32(CharType in) {\n return static_cast(\n static_cast::type>(in));\n}\n\n} // namespace\n\nnamespace internal {\n\n// Delegates to PrintBytesInObjectToImpl() to print the bytes in the\n// given object. The delegation simplifies the implementation, which\n// uses the << operator and thus is easier done outside of the\n// ::testing::internal namespace, which contains a << operator that\n// sometimes conflicts with the one in STL.\nvoid PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,\n ostream* os) {\n PrintBytesInObjectToImpl(obj_bytes, count, os);\n}\n\n// Depending on the value of a char (or wchar_t), we print it in one\n// of three formats:\n// - as is if it's a printable ASCII (e.g. 'a', '2', ' '),\n// - as a hexadecimal escape sequence (e.g. '\\x7F'), or\n// - as a special escape sequence (e.g. '\\r', '\\n').\nenum CharFormat {\n kAsIs,\n kHexEscape,\n kSpecialEscape\n};\n\n// Returns true if c is a printable ASCII character. We test the\n// value of c directly instead of calling isprint(), which is buggy on\n// Windows Mobile.\ninline bool IsPrintableAscii(char32_t c) { return 0x20 <= c && c <= 0x7E; }\n\n// Prints c (of type char, char8_t, char16_t, char32_t, or wchar_t) as a\n// character literal without the quotes, escaping it when necessary; returns how\n// c was formatted.\ntemplate \nstatic CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {\n const char32_t u_c = ToChar32(c);\n switch (u_c) {\n case L'\\0':\n *os << \"\\\\0\";\n break;\n case L'\\'':\n *os << \"\\\\'\";\n break;\n case L'\\\\':\n *os << \"\\\\\\\\\";\n break;\n case L'\\a':\n *os << \"\\\\a\";\n break;\n case L'\\b':\n *os << \"\\\\b\";\n break;\n case L'\\f':\n *os << \"\\\\f\";\n break;\n case L'\\n':\n *os << \"\\\\n\";\n break;\n case L'\\r':\n *os << \"\\\\r\";\n break;\n case L'\\t':\n *os << \"\\\\t\";\n break;\n case L'\\v':\n *os << \"\\\\v\";\n break;\n default:\n if (IsPrintableAscii(u_c)) {\n *os << static_cast(c);\n return kAsIs;\n } else {\n ostream::fmtflags flags = os->flags();\n *os << \"\\\\x\" << std::hex << std::uppercase << static_cast(u_c);\n os->flags(flags);\n return kHexEscape;\n }\n }\n return kSpecialEscape;\n}\n\n// Prints a char32_t c as if it's part of a string literal, escaping it when\n// necessary; returns how c was formatted.\nstatic CharFormat PrintAsStringLiteralTo(char32_t c, ostream* os) {\n switch (c) {\n case L'\\'':\n *os << \"'\";\n return kAsIs;\n case L'\"':\n *os << \"\\\\\\\"\";\n return kSpecialEscape;\n default:\n return PrintAsCharLiteralTo(c, os);\n }\n}\n\nstatic const char* GetCharWidthPrefix(char) {\n return \"\";\n}\n\nstatic const char* GetCharWidthPrefix(signed char) {\n return \"\";\n}\n\nstatic const char* GetCharWidthPrefix(unsigned char) {\n return \"\";\n}\n\n#ifdef __cpp_char8_t\nstatic const char* GetCharWidthPrefix(char8_t) {\n return \"u8\";\n}\n#endif\n\nstatic const char* GetCharWidthPrefix(char16_t) {\n return \"u\";\n}\n\nstatic const char* GetCharWidthPrefix(char32_t) {\n return \"U\";\n}\n\nstatic const char* GetCharWidthPrefix(wchar_t) {\n return \"L\";\n}\n\n// Prints a char c as if it's part of a string literal, escaping it when\n// necessary; returns how c was formatted.\nstatic CharFormat PrintAsStringLiteralTo(char c, ostream* os) {\n return PrintAsStringLiteralTo(ToChar32(c), os);\n}\n\n#ifdef __cpp_char8_t\nstatic CharFormat PrintAsStringLiteralTo(char8_t c, ostream* os) {\n return PrintAsStringLiteralTo(ToChar32(c), os);\n}\n#endif\n\nstatic CharFormat PrintAsStringLiteralTo(char16_t c, ostream* os) {\n return PrintAsStringLiteralTo(ToChar32(c), os);\n}\n\nstatic CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {\n return PrintAsStringLiteralTo(ToChar32(c), os);\n}\n\n// Prints a character c (of type char, char8_t, char16_t, char32_t, or wchar_t)\n// and its code. '\\0' is printed as \"'\\\\0'\", other unprintable characters are\n// also properly escaped using the standard C++ escape sequence.\ntemplate \nvoid PrintCharAndCodeTo(Char c, ostream* os) {\n // First, print c as a literal in the most readable form we can find.\n *os << GetCharWidthPrefix(c) << \"'\";\n const CharFormat format = PrintAsCharLiteralTo(c, os);\n *os << \"'\";\n\n // To aid user debugging, we also print c's code in decimal, unless\n // it's 0 (in which case c was printed as '\\\\0', making the code\n // obvious).\n if (c == 0)\n return;\n *os << \" (\" << static_cast(c);\n\n // For more convenience, we print c's code again in hexadecimal,\n // unless c was already printed in the form '\\x##' or the code is in\n // [1, 9].\n if (format == kHexEscape || (1 <= c && c <= 9)) {\n // Do nothing.\n } else {\n *os << \", 0x\" << String::FormatHexInt(static_cast(c));\n }\n *os << \")\";\n}\n\nvoid PrintTo(unsigned char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }\nvoid PrintTo(signed char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }\n\n// Prints a wchar_t as a symbol if it is printable or as its internal\n// code otherwise and also as its code. L'\\0' is printed as \"L'\\\\0'\".\nvoid PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo(wc, os); }\n\n// TODO(dcheng): Consider making this delegate to PrintCharAndCodeTo() as well.\nvoid PrintTo(char32_t c, ::std::ostream* os) {\n *os << std::hex << \"U+\" << std::uppercase << std::setfill('0') << std::setw(4)\n << static_cast(c);\n}\n\n// Prints the given array of characters to the ostream. CharType must be either\n// char, char8_t, char16_t, char32_t, or wchar_t.\n// The array starts at begin, the length is len, it may include '\\0' characters\n// and may not be NUL-terminated.\ntemplate \nGTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_\nGTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_\nGTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_\nGTEST_ATTRIBUTE_NO_SANITIZE_THREAD_\nstatic CharFormat PrintCharsAsStringTo(\n const CharType* begin, size_t len, ostream* os) {\n const char* const quote_prefix = GetCharWidthPrefix(*begin);\n *os << quote_prefix << \"\\\"\";\n bool is_previous_hex = false;\n CharFormat print_format = kAsIs;\n for (size_t index = 0; index < len; ++index) {\n const CharType cur = begin[index];\n if (is_previous_hex && IsXDigit(cur)) {\n // Previous character is of '\\x..' form and this character can be\n // interpreted as another hexadecimal digit in its number. Break string to\n // disambiguate.\n *os << \"\\\" \" << quote_prefix << \"\\\"\";\n }\n is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;\n // Remember if any characters required hex escaping.\n if (is_previous_hex) {\n print_format = kHexEscape;\n }\n }\n *os << \"\\\"\";\n return print_format;\n}\n\n// Prints a (const) char/wchar_t array of 'len' elements, starting at address\n// 'begin'. CharType must be either char or wchar_t.\ntemplate \nGTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_\nGTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_\nGTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_\nGTEST_ATTRIBUTE_NO_SANITIZE_THREAD_\nstatic void UniversalPrintCharArray(\n const CharType* begin, size_t len, ostream* os) {\n // The code\n // const char kFoo[] = \"foo\";\n // generates an array of 4, not 3, elements, with the last one being '\\0'.\n //\n // Therefore when printing a char array, we don't print the last element if\n // it's '\\0', such that the output matches the string literal as it's\n // written in the source code.\n if (len > 0 && begin[len - 1] == '\\0') {\n PrintCharsAsStringTo(begin, len - 1, os);\n return;\n }\n\n // If, however, the last element in the array is not '\\0', e.g.\n // const char kFoo[] = { 'f', 'o', 'o' };\n // we must print the entire array. We also print a message to indicate\n // that the array is not NUL-terminated.\n PrintCharsAsStringTo(begin, len, os);\n *os << \" (no terminating NUL)\";\n}\n\n// Prints a (const) char array of 'len' elements, starting at address 'begin'.\nvoid UniversalPrintArray(const char* begin, size_t len, ostream* os) {\n UniversalPrintCharArray(begin, len, os);\n}\n\n#ifdef __cpp_char8_t\n// Prints a (const) char8_t array of 'len' elements, starting at address\n// 'begin'.\nvoid UniversalPrintArray(const char8_t* begin, size_t len, ostream* os) {\n UniversalPrintCharArray(begin, len, os);\n}\n#endif\n\n// Prints a (const) char16_t array of 'len' elements, starting at address\n// 'begin'.\nvoid UniversalPrintArray(const char16_t* begin, size_t len, ostream* os) {\n UniversalPrintCharArray(begin, len, os);\n}\n\n// Prints a (const) char32_t array of 'len' elements, starting at address\n// 'begin'.\nvoid UniversalPrintArray(const char32_t* begin, size_t len, ostream* os) {\n UniversalPrintCharArray(begin, len, os);\n}\n\n// Prints a (const) wchar_t array of 'len' elements, starting at address\n// 'begin'.\nvoid UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {\n UniversalPrintCharArray(begin, len, os);\n}\n\nnamespace {\n\n// Prints a null-terminated C-style string to the ostream.\ntemplate \nvoid PrintCStringTo(const Char* s, ostream* os) {\n if (s == nullptr) {\n *os << \"NULL\";\n } else {\n *os << ImplicitCast_(s) << \" pointing to \";\n PrintCharsAsStringTo(s, std::char_traits::length(s), os);\n }\n}\n\n} // anonymous namespace\n\nvoid PrintTo(const char* s, ostream* os) { PrintCStringTo(s, os); }\n\n#ifdef __cpp_char8_t\nvoid PrintTo(const char8_t* s, ostream* os) { PrintCStringTo(s, os); }\n#endif\n\nvoid PrintTo(const char16_t* s, ostream* os) { PrintCStringTo(s, os); }\n\nvoid PrintTo(const char32_t* s, ostream* os) { PrintCStringTo(s, os); }\n\n// MSVC compiler can be configured to define whar_t as a typedef\n// of unsigned short. Defining an overload for const wchar_t* in that case\n// would cause pointers to unsigned shorts be printed as wide strings,\n// possibly accessing more memory than intended and causing invalid\n// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when\n// wchar_t is implemented as a native type.\n#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)\n// Prints the given wide C string to the ostream.\nvoid PrintTo(const wchar_t* s, ostream* os) { PrintCStringTo(s, os); }\n#endif // wchar_t is native\n\nnamespace {\n\nbool ContainsUnprintableControlCodes(const char* str, size_t length) {\n const unsigned char *s = reinterpret_cast(str);\n\n for (size_t i = 0; i < length; i++) {\n unsigned char ch = *s++;\n if (std::iscntrl(ch)) {\n switch (ch) {\n case '\\t':\n case '\\n':\n case '\\r':\n break;\n default:\n return true;\n }\n }\n }\n return false;\n}\n\nbool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; }\n\nbool IsValidUTF8(const char* str, size_t length) {\n const unsigned char *s = reinterpret_cast(str);\n\n for (size_t i = 0; i < length;) {\n unsigned char lead = s[i++];\n\n if (lead <= 0x7f) {\n continue; // single-byte character (ASCII) 0..7F\n }\n if (lead < 0xc2) {\n return false; // trail byte or non-shortest form\n } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {\n ++i; // 2-byte character\n } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&\n IsUTF8TrailByte(s[i]) &&\n IsUTF8TrailByte(s[i + 1]) &&\n // check for non-shortest form and surrogate\n (lead != 0xe0 || s[i] >= 0xa0) &&\n (lead != 0xed || s[i] < 0xa0)) {\n i += 2; // 3-byte character\n } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&\n IsUTF8TrailByte(s[i]) &&\n IsUTF8TrailByte(s[i + 1]) &&\n IsUTF8TrailByte(s[i + 2]) &&\n // check for non-shortest form\n (lead != 0xf0 || s[i] >= 0x90) &&\n (lead != 0xf4 || s[i] < 0x90)) {\n i += 3; // 4-byte character\n } else {\n return false;\n }\n }\n return true;\n}\n\nvoid ConditionalPrintAsText(const char* str, size_t length, ostream* os) {\n if (!ContainsUnprintableControlCodes(str, length) &&\n IsValidUTF8(str, length)) {\n *os << \"\\n As Text: \\\"\" << str << \"\\\"\";\n }\n}\n\n} // anonymous namespace\n\nvoid PrintStringTo(const ::std::string& s, ostream* os) {\n if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {\n if (GTEST_FLAG(print_utf8)) {\n ConditionalPrintAsText(s.data(), s.size(), os);\n }\n }\n}\n\n#ifdef __cpp_char8_t\nvoid PrintU8StringTo(const ::std::u8string& s, ostream* os) {\n PrintCharsAsStringTo(s.data(), s.size(), os);\n}\n#endif\n\nvoid PrintU16StringTo(const ::std::u16string& s, ostream* os) {\n PrintCharsAsStringTo(s.data(), s.size(), os);\n}\n\nvoid PrintU32StringTo(const ::std::u32string& s, ostream* os) {\n PrintCharsAsStringTo(s.data(), s.size(), os);\n}\n\n#if GTEST_HAS_STD_WSTRING\nvoid PrintWideStringTo(const ::std::wstring& s, ostream* os) {\n PrintCharsAsStringTo(s.data(), s.size(), os);\n}\n#endif // GTEST_HAS_STD_WSTRING\n\n} // namespace internal\n\n} // namespace testing\n// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// The Google C++ Testing and Mocking Framework (Google Test)\n\n\n\nnamespace testing {\n\nusing internal::GetUnitTestImpl;\n\n// Gets the summary of the failure message by omitting the stack trace\n// in it.\nstd::string TestPartResult::ExtractSummary(const char* message) {\n const char* const stack_trace = strstr(message, internal::kStackTraceMarker);\n return stack_trace == nullptr ? message : std::string(message, stack_trace);\n}\n\n// Prints a TestPartResult object.\nstd::ostream& operator<<(std::ostream& os, const TestPartResult& result) {\n return os << internal::FormatFileLocation(result.file_name(),\n result.line_number())\n << \" \"\n << (result.type() == TestPartResult::kSuccess\n ? \"Success\"\n : result.type() == TestPartResult::kSkip\n ? \"Skipped\"\n : result.type() == TestPartResult::kFatalFailure\n ? \"Fatal failure\"\n : \"Non-fatal failure\")\n << \":\\n\"\n << result.message() << std::endl;\n}\n\n// Appends a TestPartResult to the array.\nvoid TestPartResultArray::Append(const TestPartResult& result) {\n array_.push_back(result);\n}\n\n// Returns the TestPartResult at the given index (0-based).\nconst TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {\n if (index < 0 || index >= size()) {\n printf(\"\\nInvalid index (%d) into TestPartResultArray.\\n\", index);\n internal::posix::Abort();\n }\n\n return array_[static_cast(index)];\n}\n\n// Returns the number of TestPartResult objects in the array.\nint TestPartResultArray::size() const {\n return static_cast(array_.size());\n}\n\nnamespace internal {\n\nHasNewFatalFailureHelper::HasNewFatalFailureHelper()\n : has_new_fatal_failure_(false),\n original_reporter_(GetUnitTestImpl()->\n GetTestPartResultReporterForCurrentThread()) {\n GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);\n}\n\nHasNewFatalFailureHelper::~HasNewFatalFailureHelper() {\n GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(\n original_reporter_);\n}\n\nvoid HasNewFatalFailureHelper::ReportTestPartResult(\n const TestPartResult& result) {\n if (result.fatally_failed())\n has_new_fatal_failure_ = true;\n original_reporter_->ReportTestPartResult(result);\n}\n\n} // namespace internal\n\n} // namespace testing\n// Copyright 2008 Google Inc.\n// All Rights Reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n\nnamespace testing {\nnamespace internal {\n\n// Skips to the first non-space char in str. Returns an empty string if str\n// contains only whitespace characters.\nstatic const char* SkipSpaces(const char* str) {\n while (IsSpace(*str))\n str++;\n return str;\n}\n\nstatic std::vector SplitIntoTestNames(const char* src) {\n std::vector name_vec;\n src = SkipSpaces(src);\n for (; src != nullptr; src = SkipComma(src)) {\n name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));\n }\n return name_vec;\n}\n\n// Verifies that registered_tests match the test names in\n// registered_tests_; returns registered_tests if successful, or\n// aborts the program otherwise.\nconst char* TypedTestSuitePState::VerifyRegisteredTestNames(\n const char* test_suite_name, const char* file, int line,\n const char* registered_tests) {\n RegisterTypeParameterizedTestSuite(test_suite_name, CodeLocation(file, line));\n\n typedef RegisteredTestsMap::const_iterator RegisteredTestIter;\n registered_ = true;\n\n std::vector name_vec = SplitIntoTestNames(registered_tests);\n\n Message errors;\n\n std::set tests;\n for (std::vector::const_iterator name_it = name_vec.begin();\n name_it != name_vec.end(); ++name_it) {\n const std::string& name = *name_it;\n if (tests.count(name) != 0) {\n errors << \"Test \" << name << \" is listed more than once.\\n\";\n continue;\n }\n\n if (registered_tests_.count(name) != 0) {\n tests.insert(name);\n } else {\n errors << \"No test named \" << name\n << \" can be found in this test suite.\\n\";\n }\n }\n\n for (RegisteredTestIter it = registered_tests_.begin();\n it != registered_tests_.end();\n ++it) {\n if (tests.count(it->first) == 0) {\n errors << \"You forgot to list test \" << it->first << \".\\n\";\n }\n }\n\n const std::string& errors_str = errors.GetString();\n if (errors_str != \"\") {\n fprintf(stderr, \"%s %s\", FormatFileLocation(file, line).c_str(),\n errors_str.c_str());\n fflush(stderr);\n posix::Abort();\n }\n\n return registered_tests;\n}\n\n} // namespace internal\n} // namespace testing\n// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// Google C++ Mocking Framework (Google Mock)\n//\n// This file #includes all Google Mock implementation .cc files. The\n// purpose is to allow a user to build Google Mock by compiling this\n// file alone.\n\n// This line ensures that gmock.h can be compiled on its own, even\n// when it's fused.\n#include \"gmock/gmock.h\"\n\n// The following lines pull in the real gmock *.cc files.\n// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file implements cardinalities.\n\n\n#include \n#include // NOLINT\n#include \n#include \n\nnamespace testing {\n\nnamespace {\n\n// Implements the Between(m, n) cardinality.\nclass BetweenCardinalityImpl : public CardinalityInterface {\n public:\n BetweenCardinalityImpl(int min, int max)\n : min_(min >= 0 ? min : 0),\n max_(max >= min_ ? max : min_) {\n std::stringstream ss;\n if (min < 0) {\n ss << \"The invocation lower bound must be >= 0, \"\n << \"but is actually \" << min << \".\";\n internal::Expect(false, __FILE__, __LINE__, ss.str());\n } else if (max < 0) {\n ss << \"The invocation upper bound must be >= 0, \"\n << \"but is actually \" << max << \".\";\n internal::Expect(false, __FILE__, __LINE__, ss.str());\n } else if (min > max) {\n ss << \"The invocation upper bound (\" << max\n << \") must be >= the invocation lower bound (\" << min\n << \").\";\n internal::Expect(false, __FILE__, __LINE__, ss.str());\n }\n }\n\n // Conservative estimate on the lower/upper bound of the number of\n // calls allowed.\n int ConservativeLowerBound() const override { return min_; }\n int ConservativeUpperBound() const override { return max_; }\n\n bool IsSatisfiedByCallCount(int call_count) const override {\n return min_ <= call_count && call_count <= max_;\n }\n\n bool IsSaturatedByCallCount(int call_count) const override {\n return call_count >= max_;\n }\n\n void DescribeTo(::std::ostream* os) const override;\n\n private:\n const int min_;\n const int max_;\n\n GTEST_DISALLOW_COPY_AND_ASSIGN_(BetweenCardinalityImpl);\n};\n\n// Formats \"n times\" in a human-friendly way.\ninline std::string FormatTimes(int n) {\n if (n == 1) {\n return \"once\";\n } else if (n == 2) {\n return \"twice\";\n } else {\n std::stringstream ss;\n ss << n << \" times\";\n return ss.str();\n }\n}\n\n// Describes the Between(m, n) cardinality in human-friendly text.\nvoid BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const {\n if (min_ == 0) {\n if (max_ == 0) {\n *os << \"never called\";\n } else if (max_ == INT_MAX) {\n *os << \"called any number of times\";\n } else {\n *os << \"called at most \" << FormatTimes(max_);\n }\n } else if (min_ == max_) {\n *os << \"called \" << FormatTimes(min_);\n } else if (max_ == INT_MAX) {\n *os << \"called at least \" << FormatTimes(min_);\n } else {\n // 0 < min_ < max_ < INT_MAX\n *os << \"called between \" << min_ << \" and \" << max_ << \" times\";\n }\n}\n\n} // Unnamed namespace\n\n// Describes the given call count to an ostream.\nvoid Cardinality::DescribeActualCallCountTo(int actual_call_count,\n ::std::ostream* os) {\n if (actual_call_count > 0) {\n *os << \"called \" << FormatTimes(actual_call_count);\n } else {\n *os << \"never called\";\n }\n}\n\n// Creates a cardinality that allows at least n calls.\nGTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); }\n\n// Creates a cardinality that allows at most n calls.\nGTEST_API_ Cardinality AtMost(int n) { return Between(0, n); }\n\n// Creates a cardinality that allows any number of calls.\nGTEST_API_ Cardinality AnyNumber() { return AtLeast(0); }\n\n// Creates a cardinality that allows between min and max calls.\nGTEST_API_ Cardinality Between(int min, int max) {\n return Cardinality(new BetweenCardinalityImpl(min, max));\n}\n\n// Creates a cardinality that allows exactly n calls.\nGTEST_API_ Cardinality Exactly(int n) { return Between(n, n); }\n\n} // namespace testing\n// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file defines some utilities useful for implementing Google\n// Mock. They are subject to change without notice, so please DO NOT\n// USE THEM IN USER CODE.\n\n\n#include \n#include // NOLINT\n#include \n\nnamespace testing {\nnamespace internal {\n\n// Joins a vector of strings as if they are fields of a tuple; returns\n// the joined string.\nGTEST_API_ std::string JoinAsTuple(const Strings& fields) {\n switch (fields.size()) {\n case 0:\n return \"\";\n case 1:\n return fields[0];\n default:\n std::string result = \"(\" + fields[0];\n for (size_t i = 1; i < fields.size(); i++) {\n result += \", \";\n result += fields[i];\n }\n result += \")\";\n return result;\n }\n}\n\n// Converts an identifier name to a space-separated list of lower-case\n// words. Each maximum substring of the form [A-Za-z][a-z]*|\\d+ is\n// treated as one word. For example, both \"FooBar123\" and\n// \"foo_bar_123\" are converted to \"foo bar 123\".\nGTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {\n std::string result;\n char prev_char = '\\0';\n for (const char* p = id_name; *p != '\\0'; prev_char = *(p++)) {\n // We don't care about the current locale as the input is\n // guaranteed to be a valid C++ identifier name.\n const bool starts_new_word = IsUpper(*p) ||\n (!IsAlpha(prev_char) && IsLower(*p)) ||\n (!IsDigit(prev_char) && IsDigit(*p));\n\n if (IsAlNum(*p)) {\n if (starts_new_word && result != \"\")\n result += ' ';\n result += ToLower(*p);\n }\n }\n return result;\n}\n\n// This class reports Google Mock failures as Google Test failures. A\n// user can define another class in a similar fashion if they intend to\n// use Google Mock with a testing framework other than Google Test.\nclass GoogleTestFailureReporter : public FailureReporterInterface {\n public:\n void ReportFailure(FailureType type, const char* file, int line,\n const std::string& message) override {\n AssertHelper(type == kFatal ?\n TestPartResult::kFatalFailure :\n TestPartResult::kNonFatalFailure,\n file,\n line,\n message.c_str()) = Message();\n if (type == kFatal) {\n posix::Abort();\n }\n }\n};\n\n// Returns the global failure reporter. Will create a\n// GoogleTestFailureReporter and return it the first time called.\nGTEST_API_ FailureReporterInterface* GetFailureReporter() {\n // Points to the global failure reporter used by Google Mock. gcc\n // guarantees that the following use of failure_reporter is\n // thread-safe. We may need to add additional synchronization to\n // protect failure_reporter if we port Google Mock to other\n // compilers.\n static FailureReporterInterface* const failure_reporter =\n new GoogleTestFailureReporter();\n return failure_reporter;\n}\n\n// Protects global resources (stdout in particular) used by Log().\nstatic GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);\n\n// Returns true if and only if a log with the given severity is visible\n// according to the --gmock_verbose flag.\nGTEST_API_ bool LogIsVisible(LogSeverity severity) {\n if (GMOCK_FLAG(verbose) == kInfoVerbosity) {\n // Always show the log if --gmock_verbose=info.\n return true;\n } else if (GMOCK_FLAG(verbose) == kErrorVerbosity) {\n // Always hide it if --gmock_verbose=error.\n return false;\n } else {\n // If --gmock_verbose is neither \"info\" nor \"error\", we treat it\n // as \"warning\" (its default value).\n return severity == kWarning;\n }\n}\n\n// Prints the given message to stdout if and only if 'severity' >= the level\n// specified by the --gmock_verbose flag. If stack_frames_to_skip >=\n// 0, also prints the stack trace excluding the top\n// stack_frames_to_skip frames. In opt mode, any positive\n// stack_frames_to_skip is treated as 0, since we don't know which\n// function calls will be inlined by the compiler and need to be\n// conservative.\nGTEST_API_ void Log(LogSeverity severity, const std::string& message,\n int stack_frames_to_skip) {\n if (!LogIsVisible(severity))\n return;\n\n // Ensures that logs from different threads don't interleave.\n MutexLock l(&g_log_mutex);\n\n if (severity == kWarning) {\n // Prints a GMOCK WARNING marker to make the warnings easily searchable.\n std::cout << \"\\nGMOCK WARNING:\";\n }\n // Pre-pends a new-line to message if it doesn't start with one.\n if (message.empty() || message[0] != '\\n') {\n std::cout << \"\\n\";\n }\n std::cout << message;\n if (stack_frames_to_skip >= 0) {\n#ifdef NDEBUG\n // In opt mode, we have to be conservative and skip no stack frame.\n const int actual_to_skip = 0;\n#else\n // In dbg mode, we can do what the caller tell us to do (plus one\n // for skipping this function's stack frame).\n const int actual_to_skip = stack_frames_to_skip + 1;\n#endif // NDEBUG\n\n // Appends a new-line to message if it doesn't end with one.\n if (!message.empty() && *message.rbegin() != '\\n') {\n std::cout << \"\\n\";\n }\n std::cout << \"Stack trace:\\n\"\n << ::testing::internal::GetCurrentOsStackTraceExceptTop(\n ::testing::UnitTest::GetInstance(), actual_to_skip);\n }\n std::cout << ::std::flush;\n}\n\nGTEST_API_ WithoutMatchers GetWithoutMatchers() { return WithoutMatchers(); }\n\nGTEST_API_ void IllegalDoDefault(const char* file, int line) {\n internal::Assert(\n false, file, line,\n \"You are using DoDefault() inside a composite action like \"\n \"DoAll() or WithArgs(). This is not supported for technical \"\n \"reasons. Please instead spell out the default action, or \"\n \"assign the default action to an Action variable and use \"\n \"the variable in various places.\");\n}\n\n} // namespace internal\n} // namespace testing\n// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file implements Matcher, Matcher, and\n// utilities for defining matchers.\n\n\n#include \n#include \n#include \n#include \n\nnamespace testing {\nnamespace internal {\n\n// Returns the description for a matcher defined using the MATCHER*()\n// macro where the user-supplied description string is \"\", if\n// 'negation' is false; otherwise returns the description of the\n// negation of the matcher. 'param_values' contains a list of strings\n// that are the print-out of the matcher's parameters.\nGTEST_API_ std::string FormatMatcherDescription(bool negation,\n const char* matcher_name,\n const Strings& param_values) {\n std::string result = ConvertIdentifierNameToWords(matcher_name);\n if (param_values.size() >= 1) result += \" \" + JoinAsTuple(param_values);\n return negation ? \"not (\" + result + \")\" : result;\n}\n\n// FindMaxBipartiteMatching and its helper class.\n//\n// Uses the well-known Ford-Fulkerson max flow method to find a maximum\n// bipartite matching. Flow is considered to be from left to right.\n// There is an implicit source node that is connected to all of the left\n// nodes, and an implicit sink node that is connected to all of the\n// right nodes. All edges have unit capacity.\n//\n// Neither the flow graph nor the residual flow graph are represented\n// explicitly. Instead, they are implied by the information in 'graph' and\n// a vector called 'left_' whose elements are initialized to the\n// value kUnused. This represents the initial state of the algorithm,\n// where the flow graph is empty, and the residual flow graph has the\n// following edges:\n// - An edge from source to each left_ node\n// - An edge from each right_ node to sink\n// - An edge from each left_ node to each right_ node, if the\n// corresponding edge exists in 'graph'.\n//\n// When the TryAugment() method adds a flow, it sets left_[l] = r for some\n// nodes l and r. This induces the following changes:\n// - The edges (source, l), (l, r), and (r, sink) are added to the\n// flow graph.\n// - The same three edges are removed from the residual flow graph.\n// - The reverse edges (l, source), (r, l), and (sink, r) are added\n// to the residual flow graph, which is a directional graph\n// representing unused flow capacity.\n//\n// When the method augments a flow (moving left_[l] from some r1 to some\n// other r2), this can be thought of as \"undoing\" the above steps with\n// respect to r1 and \"redoing\" them with respect to r2.\n//\n// It bears repeating that the flow graph and residual flow graph are\n// never represented explicitly, but can be derived by looking at the\n// information in 'graph' and in left_.\n//\n// As an optimization, there is a second vector called right_ which\n// does not provide any new information. Instead, it enables more\n// efficient queries about edges entering or leaving the right-side nodes\n// of the flow or residual flow graphs. The following invariants are\n// maintained:\n//\n// left[l] == kUnused or right[left[l]] == l\n// right[r] == kUnused or left[right[r]] == r\n//\n// . [ source ] .\n// . ||| .\n// . ||| .\n// . ||\\--> left[0]=1 ---\\ right[0]=-1 ----\\ .\n// . || | | .\n// . |\\---> left[1]=-1 \\--> right[1]=0 ---\\| .\n// . | || .\n// . \\----> left[2]=2 ------> right[2]=2 --\\|| .\n// . ||| .\n// . elements matchers vvv .\n// . [ sink ] .\n//\n// See Also:\n// [1] Cormen, et al (2001). \"Section 26.2: The Ford-Fulkerson method\".\n// \"Introduction to Algorithms (Second ed.)\", pp. 651-664.\n// [2] \"Ford-Fulkerson algorithm\", Wikipedia,\n// 'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'\nclass MaxBipartiteMatchState {\n public:\n explicit MaxBipartiteMatchState(const MatchMatrix& graph)\n : graph_(&graph),\n left_(graph_->LhsSize(), kUnused),\n right_(graph_->RhsSize(), kUnused) {}\n\n // Returns the edges of a maximal match, each in the form {left, right}.\n ElementMatcherPairs Compute() {\n // 'seen' is used for path finding { 0: unseen, 1: seen }.\n ::std::vector seen;\n // Searches the residual flow graph for a path from each left node to\n // the sink in the residual flow graph, and if one is found, add flow\n // to the graph. It's okay to search through the left nodes once. The\n // edge from the implicit source node to each previously-visited left\n // node will have flow if that left node has any path to the sink\n // whatsoever. Subsequent augmentations can only add flow to the\n // network, and cannot take away that previous flow unit from the source.\n // Since the source-to-left edge can only carry one flow unit (or,\n // each element can be matched to only one matcher), there is no need\n // to visit the left nodes more than once looking for augmented paths.\n // The flow is known to be possible or impossible by looking at the\n // node once.\n for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {\n // Reset the path-marking vector and try to find a path from\n // source to sink starting at the left_[ilhs] node.\n GTEST_CHECK_(left_[ilhs] == kUnused)\n << \"ilhs: \" << ilhs << \", left_[ilhs]: \" << left_[ilhs];\n // 'seen' initialized to 'graph_->RhsSize()' copies of 0.\n seen.assign(graph_->RhsSize(), 0);\n TryAugment(ilhs, &seen);\n }\n ElementMatcherPairs result;\n for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) {\n size_t irhs = left_[ilhs];\n if (irhs == kUnused) continue;\n result.push_back(ElementMatcherPair(ilhs, irhs));\n }\n return result;\n }\n\n private:\n static const size_t kUnused = static_cast(-1);\n\n // Perform a depth-first search from left node ilhs to the sink. If a\n // path is found, flow is added to the network by linking the left and\n // right vector elements corresponding each segment of the path.\n // Returns true if a path to sink was found, which means that a unit of\n // flow was added to the network. The 'seen' vector elements correspond\n // to right nodes and are marked to eliminate cycles from the search.\n //\n // Left nodes will only be explored at most once because they\n // are accessible from at most one right node in the residual flow\n // graph.\n //\n // Note that left_[ilhs] is the only element of left_ that TryAugment will\n // potentially transition from kUnused to another value. Any other\n // left_ element holding kUnused before TryAugment will be holding it\n // when TryAugment returns.\n //\n bool TryAugment(size_t ilhs, ::std::vector* seen) {\n for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {\n if ((*seen)[irhs]) continue;\n if (!graph_->HasEdge(ilhs, irhs)) continue;\n // There's an available edge from ilhs to irhs.\n (*seen)[irhs] = 1;\n // Next a search is performed to determine whether\n // this edge is a dead end or leads to the sink.\n //\n // right_[irhs] == kUnused means that there is residual flow from\n // right node irhs to the sink, so we can use that to finish this\n // flow path and return success.\n //\n // Otherwise there is residual flow to some ilhs. We push flow\n // along that path and call ourselves recursively to see if this\n // ultimately leads to sink.\n if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) {\n // Add flow from left_[ilhs] to right_[irhs].\n left_[ilhs] = irhs;\n right_[irhs] = ilhs;\n return true;\n }\n }\n return false;\n }\n\n const MatchMatrix* graph_; // not owned\n // Each element of the left_ vector represents a left hand side node\n // (i.e. an element) and each element of right_ is a right hand side\n // node (i.e. a matcher). The values in the left_ vector indicate\n // outflow from that node to a node on the right_ side. The values\n // in the right_ indicate inflow, and specify which left_ node is\n // feeding that right_ node, if any. For example, left_[3] == 1 means\n // there's a flow from element #3 to matcher #1. Such a flow would also\n // be redundantly represented in the right_ vector as right_[1] == 3.\n // Elements of left_ and right_ are either kUnused or mutually\n // referent. Mutually referent means that left_[right_[i]] = i and\n // right_[left_[i]] = i.\n ::std::vector left_;\n ::std::vector right_;\n};\n\nconst size_t MaxBipartiteMatchState::kUnused;\n\nGTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g) {\n return MaxBipartiteMatchState(g).Compute();\n}\n\nstatic void LogElementMatcherPairVec(const ElementMatcherPairs& pairs,\n ::std::ostream* stream) {\n typedef ElementMatcherPairs::const_iterator Iter;\n ::std::ostream& os = *stream;\n os << \"{\";\n const char* sep = \"\";\n for (Iter it = pairs.begin(); it != pairs.end(); ++it) {\n os << sep << \"\\n (\"\n << \"element #\" << it->first << \", \"\n << \"matcher #\" << it->second << \")\";\n sep = \",\";\n }\n os << \"\\n}\";\n}\n\nbool MatchMatrix::NextGraph() {\n for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {\n for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {\n char& b = matched_[SpaceIndex(ilhs, irhs)];\n if (!b) {\n b = 1;\n return true;\n }\n b = 0;\n }\n }\n return false;\n}\n\nvoid MatchMatrix::Randomize() {\n for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {\n for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {\n char& b = matched_[SpaceIndex(ilhs, irhs)];\n b = static_cast(rand() & 1); // NOLINT\n }\n }\n}\n\nstd::string MatchMatrix::DebugString() const {\n ::std::stringstream ss;\n const char* sep = \"\";\n for (size_t i = 0; i < LhsSize(); ++i) {\n ss << sep;\n for (size_t j = 0; j < RhsSize(); ++j) {\n ss << HasEdge(i, j);\n }\n sep = \";\";\n }\n return ss.str();\n}\n\nvoid UnorderedElementsAreMatcherImplBase::DescribeToImpl(\n ::std::ostream* os) const {\n switch (match_flags()) {\n case UnorderedMatcherRequire::ExactMatch:\n if (matcher_describers_.empty()) {\n *os << \"is empty\";\n return;\n }\n if (matcher_describers_.size() == 1) {\n *os << \"has \" << Elements(1) << \" and that element \";\n matcher_describers_[0]->DescribeTo(os);\n return;\n }\n *os << \"has \" << Elements(matcher_describers_.size())\n << \" and there exists some permutation of elements such that:\\n\";\n break;\n case UnorderedMatcherRequire::Superset:\n *os << \"a surjection from elements to requirements exists such that:\\n\";\n break;\n case UnorderedMatcherRequire::Subset:\n *os << \"an injection from elements to requirements exists such that:\\n\";\n break;\n }\n\n const char* sep = \"\";\n for (size_t i = 0; i != matcher_describers_.size(); ++i) {\n *os << sep;\n if (match_flags() == UnorderedMatcherRequire::ExactMatch) {\n *os << \" - element #\" << i << \" \";\n } else {\n *os << \" - an element \";\n }\n matcher_describers_[i]->DescribeTo(os);\n if (match_flags() == UnorderedMatcherRequire::ExactMatch) {\n sep = \", and\\n\";\n } else {\n sep = \"\\n\";\n }\n }\n}\n\nvoid UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(\n ::std::ostream* os) const {\n switch (match_flags()) {\n case UnorderedMatcherRequire::ExactMatch:\n if (matcher_describers_.empty()) {\n *os << \"isn't empty\";\n return;\n }\n if (matcher_describers_.size() == 1) {\n *os << \"doesn't have \" << Elements(1) << \", or has \" << Elements(1)\n << \" that \";\n matcher_describers_[0]->DescribeNegationTo(os);\n return;\n }\n *os << \"doesn't have \" << Elements(matcher_describers_.size())\n << \", or there exists no permutation of elements such that:\\n\";\n break;\n case UnorderedMatcherRequire::Superset:\n *os << \"no surjection from elements to requirements exists such that:\\n\";\n break;\n case UnorderedMatcherRequire::Subset:\n *os << \"no injection from elements to requirements exists such that:\\n\";\n break;\n }\n const char* sep = \"\";\n for (size_t i = 0; i != matcher_describers_.size(); ++i) {\n *os << sep;\n if (match_flags() == UnorderedMatcherRequire::ExactMatch) {\n *os << \" - element #\" << i << \" \";\n } else {\n *os << \" - an element \";\n }\n matcher_describers_[i]->DescribeTo(os);\n if (match_flags() == UnorderedMatcherRequire::ExactMatch) {\n sep = \", and\\n\";\n } else {\n sep = \"\\n\";\n }\n }\n}\n\n// Checks that all matchers match at least one element, and that all\n// elements match at least one matcher. This enables faster matching\n// and better error reporting.\n// Returns false, writing an explanation to 'listener', if and only\n// if the success criteria are not met.\nbool UnorderedElementsAreMatcherImplBase::VerifyMatchMatrix(\n const ::std::vector& element_printouts,\n const MatchMatrix& matrix, MatchResultListener* listener) const {\n bool result = true;\n ::std::vector element_matched(matrix.LhsSize(), 0);\n ::std::vector matcher_matched(matrix.RhsSize(), 0);\n\n for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) {\n for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) {\n char matched = matrix.HasEdge(ilhs, irhs);\n element_matched[ilhs] |= matched;\n matcher_matched[irhs] |= matched;\n }\n }\n\n if (match_flags() & UnorderedMatcherRequire::Superset) {\n const char* sep =\n \"where the following matchers don't match any elements:\\n\";\n for (size_t mi = 0; mi < matcher_matched.size(); ++mi) {\n if (matcher_matched[mi]) continue;\n result = false;\n if (listener->IsInterested()) {\n *listener << sep << \"matcher #\" << mi << \": \";\n matcher_describers_[mi]->DescribeTo(listener->stream());\n sep = \",\\n\";\n }\n }\n }\n\n if (match_flags() & UnorderedMatcherRequire::Subset) {\n const char* sep =\n \"where the following elements don't match any matchers:\\n\";\n const char* outer_sep = \"\";\n if (!result) {\n outer_sep = \"\\nand \";\n }\n for (size_t ei = 0; ei < element_matched.size(); ++ei) {\n if (element_matched[ei]) continue;\n result = false;\n if (listener->IsInterested()) {\n *listener << outer_sep << sep << \"element #\" << ei << \": \"\n << element_printouts[ei];\n sep = \",\\n\";\n outer_sep = \"\";\n }\n }\n }\n return result;\n}\n\nbool UnorderedElementsAreMatcherImplBase::FindPairing(\n const MatchMatrix& matrix, MatchResultListener* listener) const {\n ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix);\n\n size_t max_flow = matches.size();\n if ((match_flags() & UnorderedMatcherRequire::Superset) &&\n max_flow < matrix.RhsSize()) {\n if (listener->IsInterested()) {\n *listener << \"where no permutation of the elements can satisfy all \"\n \"matchers, and the closest match is \"\n << max_flow << \" of \" << matrix.RhsSize()\n << \" matchers with the pairings:\\n\";\n LogElementMatcherPairVec(matches, listener->stream());\n }\n return false;\n }\n if ((match_flags() & UnorderedMatcherRequire::Subset) &&\n max_flow < matrix.LhsSize()) {\n if (listener->IsInterested()) {\n *listener\n << \"where not all elements can be matched, and the closest match is \"\n << max_flow << \" of \" << matrix.RhsSize()\n << \" matchers with the pairings:\\n\";\n LogElementMatcherPairVec(matches, listener->stream());\n }\n return false;\n }\n\n if (matches.size() > 1) {\n if (listener->IsInterested()) {\n const char* sep = \"where:\\n\";\n for (size_t mi = 0; mi < matches.size(); ++mi) {\n *listener << sep << \" - element #\" << matches[mi].first\n << \" is matched by matcher #\" << matches[mi].second;\n sep = \",\\n\";\n }\n }\n }\n return true;\n}\n\n} // namespace internal\n} // namespace testing\n// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file implements the spec builder syntax (ON_CALL and\n// EXPECT_CALL).\n\n\n#include \n\n#include // NOLINT\n#include \n#include \n#include \n#include \n#include \n#include \n\n\n#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC\n# include // NOLINT\n#endif\n\n// Silence C4800 (C4800: 'int *const ': forcing value\n// to bool 'true' or 'false') for MSVC 15\n#ifdef _MSC_VER\n#if _MSC_VER == 1900\n# pragma warning(push)\n# pragma warning(disable:4800)\n#endif\n#endif\n\nnamespace testing {\nnamespace internal {\n\n// Protects the mock object registry (in class Mock), all function\n// mockers, and all expectations.\nGTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);\n\n// Logs a message including file and line number information.\nGTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,\n const char* file, int line,\n const std::string& message) {\n ::std::ostringstream s;\n s << internal::FormatFileLocation(file, line) << \" \" << message\n << ::std::endl;\n Log(severity, s.str(), 0);\n}\n\n// Constructs an ExpectationBase object.\nExpectationBase::ExpectationBase(const char* a_file, int a_line,\n const std::string& a_source_text)\n : file_(a_file),\n line_(a_line),\n source_text_(a_source_text),\n cardinality_specified_(false),\n cardinality_(Exactly(1)),\n call_count_(0),\n retired_(false),\n extra_matcher_specified_(false),\n repeated_action_specified_(false),\n retires_on_saturation_(false),\n last_clause_(kNone),\n action_count_checked_(false) {}\n\n// Destructs an ExpectationBase object.\nExpectationBase::~ExpectationBase() {}\n\n// Explicitly specifies the cardinality of this expectation. Used by\n// the subclasses to implement the .Times() clause.\nvoid ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {\n cardinality_specified_ = true;\n cardinality_ = a_cardinality;\n}\n\n// Retires all pre-requisites of this expectation.\nvoid ExpectationBase::RetireAllPreRequisites()\n GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n if (is_retired()) {\n // We can take this short-cut as we never retire an expectation\n // until we have retired all its pre-requisites.\n return;\n }\n\n ::std::vector expectations(1, this);\n while (!expectations.empty()) {\n ExpectationBase* exp = expectations.back();\n expectations.pop_back();\n\n for (ExpectationSet::const_iterator it =\n exp->immediate_prerequisites_.begin();\n it != exp->immediate_prerequisites_.end(); ++it) {\n ExpectationBase* next = it->expectation_base().get();\n if (!next->is_retired()) {\n next->Retire();\n expectations.push_back(next);\n }\n }\n }\n}\n\n// Returns true if and only if all pre-requisites of this expectation\n// have been satisfied.\nbool ExpectationBase::AllPrerequisitesAreSatisfied() const\n GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n g_gmock_mutex.AssertHeld();\n ::std::vector expectations(1, this);\n while (!expectations.empty()) {\n const ExpectationBase* exp = expectations.back();\n expectations.pop_back();\n\n for (ExpectationSet::const_iterator it =\n exp->immediate_prerequisites_.begin();\n it != exp->immediate_prerequisites_.end(); ++it) {\n const ExpectationBase* next = it->expectation_base().get();\n if (!next->IsSatisfied()) return false;\n expectations.push_back(next);\n }\n }\n return true;\n}\n\n// Adds unsatisfied pre-requisites of this expectation to 'result'.\nvoid ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const\n GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n g_gmock_mutex.AssertHeld();\n ::std::vector expectations(1, this);\n while (!expectations.empty()) {\n const ExpectationBase* exp = expectations.back();\n expectations.pop_back();\n\n for (ExpectationSet::const_iterator it =\n exp->immediate_prerequisites_.begin();\n it != exp->immediate_prerequisites_.end(); ++it) {\n const ExpectationBase* next = it->expectation_base().get();\n\n if (next->IsSatisfied()) {\n // If *it is satisfied and has a call count of 0, some of its\n // pre-requisites may not be satisfied yet.\n if (next->call_count_ == 0) {\n expectations.push_back(next);\n }\n } else {\n // Now that we know next is unsatisfied, we are not so interested\n // in whether its pre-requisites are satisfied. Therefore we\n // don't iterate into it here.\n *result += *it;\n }\n }\n }\n}\n\n// Describes how many times a function call matching this\n// expectation has occurred.\nvoid ExpectationBase::DescribeCallCountTo(::std::ostream* os) const\n GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n g_gmock_mutex.AssertHeld();\n\n // Describes how many times the function is expected to be called.\n *os << \" Expected: to be \";\n cardinality().DescribeTo(os);\n *os << \"\\n Actual: \";\n Cardinality::DescribeActualCallCountTo(call_count(), os);\n\n // Describes the state of the expectation (e.g. is it satisfied?\n // is it active?).\n *os << \" - \" << (IsOverSaturated() ? \"over-saturated\" :\n IsSaturated() ? \"saturated\" :\n IsSatisfied() ? \"satisfied\" : \"unsatisfied\")\n << \" and \"\n << (is_retired() ? \"retired\" : \"active\");\n}\n\n// Checks the action count (i.e. the number of WillOnce() and\n// WillRepeatedly() clauses) against the cardinality if this hasn't\n// been done before. Prints a warning if there are too many or too\n// few actions.\nvoid ExpectationBase::CheckActionCountIfNotDone() const\n GTEST_LOCK_EXCLUDED_(mutex_) {\n bool should_check = false;\n {\n MutexLock l(&mutex_);\n if (!action_count_checked_) {\n action_count_checked_ = true;\n should_check = true;\n }\n }\n\n if (should_check) {\n if (!cardinality_specified_) {\n // The cardinality was inferred - no need to check the action\n // count against it.\n return;\n }\n\n // The cardinality was explicitly specified.\n const int action_count = static_cast(untyped_actions_.size());\n const int upper_bound = cardinality().ConservativeUpperBound();\n const int lower_bound = cardinality().ConservativeLowerBound();\n bool too_many; // True if there are too many actions, or false\n // if there are too few.\n if (action_count > upper_bound ||\n (action_count == upper_bound && repeated_action_specified_)) {\n too_many = true;\n } else if (0 < action_count && action_count < lower_bound &&\n !repeated_action_specified_) {\n too_many = false;\n } else {\n return;\n }\n\n ::std::stringstream ss;\n DescribeLocationTo(&ss);\n ss << \"Too \" << (too_many ? \"many\" : \"few\")\n << \" actions specified in \" << source_text() << \"...\\n\"\n << \"Expected to be \";\n cardinality().DescribeTo(&ss);\n ss << \", but has \" << (too_many ? \"\" : \"only \")\n << action_count << \" WillOnce()\"\n << (action_count == 1 ? \"\" : \"s\");\n if (repeated_action_specified_) {\n ss << \" and a WillRepeatedly()\";\n }\n ss << \".\";\n Log(kWarning, ss.str(), -1); // -1 means \"don't print stack trace\".\n }\n}\n\n// Implements the .Times() clause.\nvoid ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {\n if (last_clause_ == kTimes) {\n ExpectSpecProperty(false,\n \".Times() cannot appear \"\n \"more than once in an EXPECT_CALL().\");\n } else {\n ExpectSpecProperty(last_clause_ < kTimes,\n \".Times() cannot appear after \"\n \".InSequence(), .WillOnce(), .WillRepeatedly(), \"\n \"or .RetiresOnSaturation().\");\n }\n last_clause_ = kTimes;\n\n SpecifyCardinality(a_cardinality);\n}\n\n// Points to the implicit sequence introduced by a living InSequence\n// object (if any) in the current thread or NULL.\nGTEST_API_ ThreadLocal g_gmock_implicit_sequence;\n\n// Reports an uninteresting call (whose description is in msg) in the\n// manner specified by 'reaction'.\nvoid ReportUninterestingCall(CallReaction reaction, const std::string& msg) {\n // Include a stack trace only if --gmock_verbose=info is specified.\n const int stack_frames_to_skip =\n GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1;\n switch (reaction) {\n case kAllow:\n Log(kInfo, msg, stack_frames_to_skip);\n break;\n case kWarn:\n Log(kWarning,\n msg +\n \"\\nNOTE: You can safely ignore the above warning unless this \"\n \"call should not happen. Do not suppress it by blindly adding \"\n \"an EXPECT_CALL() if you don't mean to enforce the call. \"\n \"See \"\n \"https://github.com/google/googletest/blob/master/docs/\"\n \"gmock_cook_book.md#\"\n \"knowing-when-to-expect for details.\\n\",\n stack_frames_to_skip);\n break;\n default: // FAIL\n Expect(false, nullptr, -1, msg);\n }\n}\n\nUntypedFunctionMockerBase::UntypedFunctionMockerBase()\n : mock_obj_(nullptr), name_(\"\") {}\n\nUntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}\n\n// Sets the mock object this mock method belongs to, and registers\n// this information in the global mock registry. Will be called\n// whenever an EXPECT_CALL() or ON_CALL() is executed on this mock\n// method.\nvoid UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)\n GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {\n {\n MutexLock l(&g_gmock_mutex);\n mock_obj_ = mock_obj;\n }\n Mock::Register(mock_obj, this);\n}\n\n// Sets the mock object this mock method belongs to, and sets the name\n// of the mock function. Will be called upon each invocation of this\n// mock function.\nvoid UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,\n const char* name)\n GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {\n // We protect name_ under g_gmock_mutex in case this mock function\n // is called from two threads concurrently.\n MutexLock l(&g_gmock_mutex);\n mock_obj_ = mock_obj;\n name_ = name;\n}\n\n// Returns the name of the function being mocked. Must be called\n// after RegisterOwner() or SetOwnerAndName() has been called.\nconst void* UntypedFunctionMockerBase::MockObject() const\n GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {\n const void* mock_obj;\n {\n // We protect mock_obj_ under g_gmock_mutex in case this mock\n // function is called from two threads concurrently.\n MutexLock l(&g_gmock_mutex);\n Assert(mock_obj_ != nullptr, __FILE__, __LINE__,\n \"MockObject() must not be called before RegisterOwner() or \"\n \"SetOwnerAndName() has been called.\");\n mock_obj = mock_obj_;\n }\n return mock_obj;\n}\n\n// Returns the name of this mock method. Must be called after\n// SetOwnerAndName() has been called.\nconst char* UntypedFunctionMockerBase::Name() const\n GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {\n const char* name;\n {\n // We protect name_ under g_gmock_mutex in case this mock\n // function is called from two threads concurrently.\n MutexLock l(&g_gmock_mutex);\n Assert(name_ != nullptr, __FILE__, __LINE__,\n \"Name() must not be called before SetOwnerAndName() has \"\n \"been called.\");\n name = name_;\n }\n return name;\n}\n\n// Calculates the result of invoking this mock function with the given\n// arguments, prints it, and returns it. The caller is responsible\n// for deleting the result.\nUntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(\n void* const untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {\n // See the definition of untyped_expectations_ for why access to it\n // is unprotected here.\n if (untyped_expectations_.size() == 0) {\n // No expectation is set on this mock method - we have an\n // uninteresting call.\n\n // We must get Google Mock's reaction on uninteresting calls\n // made on this mock object BEFORE performing the action,\n // because the action may DELETE the mock object and make the\n // following expression meaningless.\n const CallReaction reaction =\n Mock::GetReactionOnUninterestingCalls(MockObject());\n\n // True if and only if we need to print this call's arguments and return\n // value. This definition must be kept in sync with\n // the behavior of ReportUninterestingCall().\n const bool need_to_report_uninteresting_call =\n // If the user allows this uninteresting call, we print it\n // only when they want informational messages.\n reaction == kAllow ? LogIsVisible(kInfo) :\n // If the user wants this to be a warning, we print\n // it only when they want to see warnings.\n reaction == kWarn\n ? LogIsVisible(kWarning)\n :\n // Otherwise, the user wants this to be an error, and we\n // should always print detailed information in the error.\n true;\n\n if (!need_to_report_uninteresting_call) {\n // Perform the action without printing the call information.\n return this->UntypedPerformDefaultAction(\n untyped_args, \"Function call: \" + std::string(Name()));\n }\n\n // Warns about the uninteresting call.\n ::std::stringstream ss;\n this->UntypedDescribeUninterestingCall(untyped_args, &ss);\n\n // Calculates the function result.\n UntypedActionResultHolderBase* const result =\n this->UntypedPerformDefaultAction(untyped_args, ss.str());\n\n // Prints the function result.\n if (result != nullptr) result->PrintAsActionResult(&ss);\n\n ReportUninterestingCall(reaction, ss.str());\n return result;\n }\n\n bool is_excessive = false;\n ::std::stringstream ss;\n ::std::stringstream why;\n ::std::stringstream loc;\n const void* untyped_action = nullptr;\n\n // The UntypedFindMatchingExpectation() function acquires and\n // releases g_gmock_mutex.\n\n const ExpectationBase* const untyped_expectation =\n this->UntypedFindMatchingExpectation(untyped_args, &untyped_action,\n &is_excessive, &ss, &why);\n const bool found = untyped_expectation != nullptr;\n\n // True if and only if we need to print the call's arguments\n // and return value.\n // This definition must be kept in sync with the uses of Expect()\n // and Log() in this function.\n const bool need_to_report_call =\n !found || is_excessive || LogIsVisible(kInfo);\n if (!need_to_report_call) {\n // Perform the action without printing the call information.\n return untyped_action == nullptr\n ? this->UntypedPerformDefaultAction(untyped_args, \"\")\n : this->UntypedPerformAction(untyped_action, untyped_args);\n }\n\n ss << \" Function call: \" << Name();\n this->UntypedPrintArgs(untyped_args, &ss);\n\n // In case the action deletes a piece of the expectation, we\n // generate the message beforehand.\n if (found && !is_excessive) {\n untyped_expectation->DescribeLocationTo(&loc);\n }\n\n UntypedActionResultHolderBase* result = nullptr;\n\n auto perform_action = [&, this] {\n return untyped_action == nullptr\n ? this->UntypedPerformDefaultAction(untyped_args, ss.str())\n : this->UntypedPerformAction(untyped_action, untyped_args);\n };\n auto handle_failures = [&] {\n ss << \"\\n\" << why.str();\n\n if (!found) {\n // No expectation matches this call - reports a failure.\n Expect(false, nullptr, -1, ss.str());\n } else if (is_excessive) {\n // We had an upper-bound violation and the failure message is in ss.\n Expect(false, untyped_expectation->file(), untyped_expectation->line(),\n ss.str());\n } else {\n // We had an expected call and the matching expectation is\n // described in ss.\n Log(kInfo, loc.str() + ss.str(), 2);\n }\n };\n#if GTEST_HAS_EXCEPTIONS\n try {\n result = perform_action();\n } catch (...) {\n handle_failures();\n throw;\n }\n#else\n result = perform_action();\n#endif\n\n if (result != nullptr) result->PrintAsActionResult(&ss);\n handle_failures();\n return result;\n}\n\n// Returns an Expectation object that references and co-owns exp,\n// which must be an expectation on this mock function.\nExpectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {\n // See the definition of untyped_expectations_ for why access to it\n // is unprotected here.\n for (UntypedExpectations::const_iterator it =\n untyped_expectations_.begin();\n it != untyped_expectations_.end(); ++it) {\n if (it->get() == exp) {\n return Expectation(*it);\n }\n }\n\n Assert(false, __FILE__, __LINE__, \"Cannot find expectation.\");\n return Expectation();\n // The above statement is just to make the code compile, and will\n // never be executed.\n}\n\n// Verifies that all expectations on this mock function have been\n// satisfied. Reports one or more Google Test non-fatal failures\n// and returns false if not.\nbool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()\n GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n g_gmock_mutex.AssertHeld();\n bool expectations_met = true;\n for (UntypedExpectations::const_iterator it =\n untyped_expectations_.begin();\n it != untyped_expectations_.end(); ++it) {\n ExpectationBase* const untyped_expectation = it->get();\n if (untyped_expectation->IsOverSaturated()) {\n // There was an upper-bound violation. Since the error was\n // already reported when it occurred, there is no need to do\n // anything here.\n expectations_met = false;\n } else if (!untyped_expectation->IsSatisfied()) {\n expectations_met = false;\n ::std::stringstream ss;\n ss << \"Actual function call count doesn't match \"\n << untyped_expectation->source_text() << \"...\\n\";\n // No need to show the source file location of the expectation\n // in the description, as the Expect() call that follows already\n // takes care of it.\n untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);\n untyped_expectation->DescribeCallCountTo(&ss);\n Expect(false, untyped_expectation->file(),\n untyped_expectation->line(), ss.str());\n }\n }\n\n // Deleting our expectations may trigger other mock objects to be deleted, for\n // example if an action contains a reference counted smart pointer to that\n // mock object, and that is the last reference. So if we delete our\n // expectations within the context of the global mutex we may deadlock when\n // this method is called again. Instead, make a copy of the set of\n // expectations to delete, clear our set within the mutex, and then clear the\n // copied set outside of it.\n UntypedExpectations expectations_to_delete;\n untyped_expectations_.swap(expectations_to_delete);\n\n g_gmock_mutex.Unlock();\n expectations_to_delete.clear();\n g_gmock_mutex.Lock();\n\n return expectations_met;\n}\n\nCallReaction intToCallReaction(int mock_behavior) {\n if (mock_behavior >= kAllow && mock_behavior <= kFail) {\n return static_cast(mock_behavior);\n }\n return kWarn;\n}\n\n} // namespace internal\n\n// Class Mock.\n\nnamespace {\n\ntypedef std::set FunctionMockers;\n\n// The current state of a mock object. Such information is needed for\n// detecting leaked mock objects and explicitly verifying a mock's\n// expectations.\nstruct MockObjectState {\n MockObjectState()\n : first_used_file(nullptr), first_used_line(-1), leakable(false) {}\n\n // Where in the source file an ON_CALL or EXPECT_CALL is first\n // invoked on this mock object.\n const char* first_used_file;\n int first_used_line;\n ::std::string first_used_test_suite;\n ::std::string first_used_test;\n bool leakable; // true if and only if it's OK to leak the object.\n FunctionMockers function_mockers; // All registered methods of the object.\n};\n\n// A global registry holding the state of all mock objects that are\n// alive. A mock object is added to this registry the first time\n// Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It\n// is removed from the registry in the mock object's destructor.\nclass MockObjectRegistry {\n public:\n // Maps a mock object (identified by its address) to its state.\n typedef std::map StateMap;\n\n // This destructor will be called when a program exits, after all\n // tests in it have been run. By then, there should be no mock\n // object alive. Therefore we report any living object as test\n // failure, unless the user explicitly asked us to ignore it.\n ~MockObjectRegistry() {\n if (!GMOCK_FLAG(catch_leaked_mocks))\n return;\n\n int leaked_count = 0;\n for (StateMap::const_iterator it = states_.begin(); it != states_.end();\n ++it) {\n if (it->second.leakable) // The user said it's fine to leak this object.\n continue;\n\n // FIXME: Print the type of the leaked object.\n // This can help the user identify the leaked object.\n std::cout << \"\\n\";\n const MockObjectState& state = it->second;\n std::cout << internal::FormatFileLocation(state.first_used_file,\n state.first_used_line);\n std::cout << \" ERROR: this mock object\";\n if (state.first_used_test != \"\") {\n std::cout << \" (used in test \" << state.first_used_test_suite << \".\"\n << state.first_used_test << \")\";\n }\n std::cout << \" should be deleted but never is. Its address is @\"\n << it->first << \".\";\n leaked_count++;\n }\n if (leaked_count > 0) {\n std::cout << \"\\nERROR: \" << leaked_count << \" leaked mock \"\n << (leaked_count == 1 ? \"object\" : \"objects\")\n << \" found at program exit. Expectations on a mock object are \"\n \"verified when the object is destructed. Leaking a mock \"\n \"means that its expectations aren't verified, which is \"\n \"usually a test bug. If you really intend to leak a mock, \"\n \"you can suppress this error using \"\n \"testing::Mock::AllowLeak(mock_object), or you may use a \"\n \"fake or stub instead of a mock.\\n\";\n std::cout.flush();\n ::std::cerr.flush();\n // RUN_ALL_TESTS() has already returned when this destructor is\n // called. Therefore we cannot use the normal Google Test\n // failure reporting mechanism.\n _exit(1); // We cannot call exit() as it is not reentrant and\n // may already have been called.\n }\n }\n\n StateMap& states() { return states_; }\n\n private:\n StateMap states_;\n};\n\n// Protected by g_gmock_mutex.\nMockObjectRegistry g_mock_object_registry;\n\n// Maps a mock object to the reaction Google Mock should have when an\n// uninteresting method is called. Protected by g_gmock_mutex.\nstd::unordered_map&\nUninterestingCallReactionMap() {\n static auto* map = new std::unordered_map;\n return *map;\n}\n\n// Sets the reaction Google Mock should have when an uninteresting\n// method of the given mock object is called.\nvoid SetReactionOnUninterestingCalls(uintptr_t mock_obj,\n internal::CallReaction reaction)\n GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n internal::MutexLock l(&internal::g_gmock_mutex);\n UninterestingCallReactionMap()[mock_obj] = reaction;\n}\n\n} // namespace\n\n// Tells Google Mock to allow uninteresting calls on the given mock\n// object.\nvoid Mock::AllowUninterestingCalls(uintptr_t mock_obj)\n GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);\n}\n\n// Tells Google Mock to warn the user about uninteresting calls on the\n// given mock object.\nvoid Mock::WarnUninterestingCalls(uintptr_t mock_obj)\n GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);\n}\n\n// Tells Google Mock to fail uninteresting calls on the given mock\n// object.\nvoid Mock::FailUninterestingCalls(uintptr_t mock_obj)\n GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n SetReactionOnUninterestingCalls(mock_obj, internal::kFail);\n}\n\n// Tells Google Mock the given mock object is being destroyed and its\n// entry in the call-reaction table should be removed.\nvoid Mock::UnregisterCallReaction(uintptr_t mock_obj)\n GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n internal::MutexLock l(&internal::g_gmock_mutex);\n UninterestingCallReactionMap().erase(static_cast(mock_obj));\n}\n\n// Returns the reaction Google Mock will have on uninteresting calls\n// made on the given mock object.\ninternal::CallReaction Mock::GetReactionOnUninterestingCalls(\n const void* mock_obj)\n GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n internal::MutexLock l(&internal::g_gmock_mutex);\n return (UninterestingCallReactionMap().count(\n reinterpret_cast(mock_obj)) == 0)\n ? internal::intToCallReaction(\n GMOCK_FLAG(default_mock_behavior))\n : UninterestingCallReactionMap()[reinterpret_cast(\n mock_obj)];\n}\n\n// Tells Google Mock to ignore mock_obj when checking for leaked mock\n// objects.\nvoid Mock::AllowLeak(const void* mock_obj)\n GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n internal::MutexLock l(&internal::g_gmock_mutex);\n g_mock_object_registry.states()[mock_obj].leakable = true;\n}\n\n// Verifies and clears all expectations on the given mock object. If\n// the expectations aren't satisfied, generates one or more Google\n// Test non-fatal failures and returns false.\nbool Mock::VerifyAndClearExpectations(void* mock_obj)\n GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n internal::MutexLock l(&internal::g_gmock_mutex);\n return VerifyAndClearExpectationsLocked(mock_obj);\n}\n\n// Verifies all expectations on the given mock object and clears its\n// default actions and expectations. Returns true if and only if the\n// verification was successful.\nbool Mock::VerifyAndClear(void* mock_obj)\n GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n internal::MutexLock l(&internal::g_gmock_mutex);\n ClearDefaultActionsLocked(mock_obj);\n return VerifyAndClearExpectationsLocked(mock_obj);\n}\n\n// Verifies and clears all expectations on the given mock object. If\n// the expectations aren't satisfied, generates one or more Google\n// Test non-fatal failures and returns false.\nbool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)\n GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {\n internal::g_gmock_mutex.AssertHeld();\n if (g_mock_object_registry.states().count(mock_obj) == 0) {\n // No EXPECT_CALL() was set on the given mock object.\n return true;\n }\n\n // Verifies and clears the expectations on each mock method in the\n // given mock object.\n bool expectations_met = true;\n FunctionMockers& mockers =\n g_mock_object_registry.states()[mock_obj].function_mockers;\n for (FunctionMockers::const_iterator it = mockers.begin();\n it != mockers.end(); ++it) {\n if (!(*it)->VerifyAndClearExpectationsLocked()) {\n expectations_met = false;\n }\n }\n\n // We don't clear the content of mockers, as they may still be\n // needed by ClearDefaultActionsLocked().\n return expectations_met;\n}\n\nbool Mock::IsNaggy(void* mock_obj)\n GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kWarn;\n}\nbool Mock::IsNice(void* mock_obj)\n GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kAllow;\n}\nbool Mock::IsStrict(void* mock_obj)\n GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kFail;\n}\n\n// Registers a mock object and a mock method it owns.\nvoid Mock::Register(const void* mock_obj,\n internal::UntypedFunctionMockerBase* mocker)\n GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n internal::MutexLock l(&internal::g_gmock_mutex);\n g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);\n}\n\n// Tells Google Mock where in the source code mock_obj is used in an\n// ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this\n// information helps the user identify which object it is.\nvoid Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,\n const char* file, int line)\n GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n internal::MutexLock l(&internal::g_gmock_mutex);\n MockObjectState& state = g_mock_object_registry.states()[mock_obj];\n if (state.first_used_file == nullptr) {\n state.first_used_file = file;\n state.first_used_line = line;\n const TestInfo* const test_info =\n UnitTest::GetInstance()->current_test_info();\n if (test_info != nullptr) {\n state.first_used_test_suite = test_info->test_suite_name();\n state.first_used_test = test_info->name();\n }\n }\n}\n\n// Unregisters a mock method; removes the owning mock object from the\n// registry when the last mock method associated with it has been\n// unregistered. This is called only in the destructor of\n// FunctionMockerBase.\nvoid Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)\n GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {\n internal::g_gmock_mutex.AssertHeld();\n for (MockObjectRegistry::StateMap::iterator it =\n g_mock_object_registry.states().begin();\n it != g_mock_object_registry.states().end(); ++it) {\n FunctionMockers& mockers = it->second.function_mockers;\n if (mockers.erase(mocker) > 0) {\n // mocker was in mockers and has been just removed.\n if (mockers.empty()) {\n g_mock_object_registry.states().erase(it);\n }\n return;\n }\n }\n}\n\n// Clears all ON_CALL()s set on the given mock object.\nvoid Mock::ClearDefaultActionsLocked(void* mock_obj)\n GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {\n internal::g_gmock_mutex.AssertHeld();\n\n if (g_mock_object_registry.states().count(mock_obj) == 0) {\n // No ON_CALL() was set on the given mock object.\n return;\n }\n\n // Clears the default actions for each mock method in the given mock\n // object.\n FunctionMockers& mockers =\n g_mock_object_registry.states()[mock_obj].function_mockers;\n for (FunctionMockers::const_iterator it = mockers.begin();\n it != mockers.end(); ++it) {\n (*it)->ClearDefaultActionsLocked();\n }\n\n // We don't clear the content of mockers, as they may still be\n // needed by VerifyAndClearExpectationsLocked().\n}\n\nExpectation::Expectation() {}\n\nExpectation::Expectation(\n const std::shared_ptr& an_expectation_base)\n : expectation_base_(an_expectation_base) {}\n\nExpectation::~Expectation() {}\n\n// Adds an expectation to a sequence.\nvoid Sequence::AddExpectation(const Expectation& expectation) const {\n if (*last_expectation_ != expectation) {\n if (last_expectation_->expectation_base() != nullptr) {\n expectation.expectation_base()->immediate_prerequisites_\n += *last_expectation_;\n }\n *last_expectation_ = expectation;\n }\n}\n\n// Creates the implicit sequence if there isn't one.\nInSequence::InSequence() {\n if (internal::g_gmock_implicit_sequence.get() == nullptr) {\n internal::g_gmock_implicit_sequence.set(new Sequence);\n sequence_created_ = true;\n } else {\n sequence_created_ = false;\n }\n}\n\n// Deletes the implicit sequence if it was created by the constructor\n// of this object.\nInSequence::~InSequence() {\n if (sequence_created_) {\n delete internal::g_gmock_implicit_sequence.get();\n internal::g_gmock_implicit_sequence.set(nullptr);\n }\n}\n\n} // namespace testing\n\n#ifdef _MSC_VER\n#if _MSC_VER == 1900\n# pragma warning(pop)\n#endif\n#endif\n// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\nnamespace testing {\n\nGMOCK_DEFINE_bool_(catch_leaked_mocks, true,\n \"true if and only if Google Mock should report leaked \"\n \"mock objects as failures.\");\n\nGMOCK_DEFINE_string_(verbose, internal::kWarningVerbosity,\n \"Controls how verbose Google Mock's output is.\"\n \" Valid values:\\n\"\n \" info - prints all messages.\\n\"\n \" warning - prints warnings and errors.\\n\"\n \" error - prints errors only.\");\n\nGMOCK_DEFINE_int32_(default_mock_behavior, 1,\n \"Controls the default behavior of mocks.\"\n \" Valid values:\\n\"\n \" 0 - by default, mocks act as NiceMocks.\\n\"\n \" 1 - by default, mocks act as NaggyMocks.\\n\"\n \" 2 - by default, mocks act as StrictMocks.\");\n\nnamespace internal {\n\n// Parses a string as a command line flag. The string should have the\n// format \"--gmock_flag=value\". When def_optional is true, the\n// \"=value\" part can be omitted.\n//\n// Returns the value of the flag, or NULL if the parsing failed.\nstatic const char* ParseGoogleMockFlagValue(const char* str,\n const char* flag,\n bool def_optional) {\n // str and flag must not be NULL.\n if (str == nullptr || flag == nullptr) return nullptr;\n\n // The flag must start with \"--gmock_\".\n const std::string flag_str = std::string(\"--gmock_\") + flag;\n const size_t flag_len = flag_str.length();\n if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;\n\n // Skips the flag name.\n const char* flag_end = str + flag_len;\n\n // When def_optional is true, it's OK to not have a \"=value\" part.\n if (def_optional && (flag_end[0] == '\\0')) {\n return flag_end;\n }\n\n // If def_optional is true and there are more characters after the\n // flag name, or if def_optional is false, there must be a '=' after\n // the flag name.\n if (flag_end[0] != '=') return nullptr;\n\n // Returns the string after \"=\".\n return flag_end + 1;\n}\n\n// Parses a string for a Google Mock bool flag, in the form of\n// \"--gmock_flag=value\".\n//\n// On success, stores the value of the flag in *value, and returns\n// true. On failure, returns false without changing *value.\nstatic bool ParseGoogleMockBoolFlag(const char* str, const char* flag,\n bool* value) {\n // Gets the value of the flag as a string.\n const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);\n\n // Aborts if the parsing failed.\n if (value_str == nullptr) return false;\n\n // Converts the string value to a bool.\n *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');\n return true;\n}\n\n// Parses a string for a Google Mock string flag, in the form of\n// \"--gmock_flag=value\".\n//\n// On success, stores the value of the flag in *value, and returns\n// true. On failure, returns false without changing *value.\ntemplate \nstatic bool ParseGoogleMockStringFlag(const char* str, const char* flag,\n String* value) {\n // Gets the value of the flag as a string.\n const char* const value_str = ParseGoogleMockFlagValue(str, flag, false);\n\n // Aborts if the parsing failed.\n if (value_str == nullptr) return false;\n\n // Sets *value to the value of the flag.\n *value = value_str;\n return true;\n}\n\nstatic bool ParseGoogleMockIntFlag(const char* str, const char* flag,\n int32_t* value) {\n // Gets the value of the flag as a string.\n const char* const value_str = ParseGoogleMockFlagValue(str, flag, true);\n\n // Aborts if the parsing failed.\n if (value_str == nullptr) return false;\n\n // Sets *value to the value of the flag.\n return ParseInt32(Message() << \"The value of flag --\" << flag,\n value_str, value);\n}\n\n// The internal implementation of InitGoogleMock().\n//\n// The type parameter CharType can be instantiated to either char or\n// wchar_t.\ntemplate \nvoid InitGoogleMockImpl(int* argc, CharType** argv) {\n // Makes sure Google Test is initialized. InitGoogleTest() is\n // idempotent, so it's fine if the user has already called it.\n InitGoogleTest(argc, argv);\n if (*argc <= 0) return;\n\n for (int i = 1; i != *argc; i++) {\n const std::string arg_string = StreamableToString(argv[i]);\n const char* const arg = arg_string.c_str();\n\n // Do we see a Google Mock flag?\n if (ParseGoogleMockBoolFlag(arg, \"catch_leaked_mocks\",\n &GMOCK_FLAG(catch_leaked_mocks)) ||\n ParseGoogleMockStringFlag(arg, \"verbose\", &GMOCK_FLAG(verbose)) ||\n ParseGoogleMockIntFlag(arg, \"default_mock_behavior\",\n &GMOCK_FLAG(default_mock_behavior))) {\n // Yes. Shift the remainder of the argv list left by one. Note\n // that argv has (*argc + 1) elements, the last one always being\n // NULL. The following loop moves the trailing NULL element as\n // well.\n for (int j = i; j != *argc; j++) {\n argv[j] = argv[j + 1];\n }\n\n // Decrements the argument count.\n (*argc)--;\n\n // We also need to decrement the iterator as we just removed\n // an element.\n i--;\n }\n }\n}\n\n} // namespace internal\n\n// Initializes Google Mock. This must be called before running the\n// tests. In particular, it parses a command line for the flags that\n// Google Mock recognizes. Whenever a Google Mock flag is seen, it is\n// removed from argv, and *argc is decremented.\n//\n// No value is returned. Instead, the Google Mock flag variables are\n// updated.\n//\n// Since Google Test is needed for Google Mock to work, this function\n// also initializes Google Test and parses its flags, if that hasn't\n// been done.\nGTEST_API_ void InitGoogleMock(int* argc, char** argv) {\n internal::InitGoogleMockImpl(argc, argv);\n}\n\n// This overloaded version can be used in Windows programs compiled in\n// UNICODE mode.\nGTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) {\n internal::InitGoogleMockImpl(argc, argv);\n}\n\n// This overloaded version can be used on Arduino/embedded platforms where\n// there is no argc/argv.\nGTEST_API_ void InitGoogleMock() {\n // Since Arduino doesn't have a command line, fake out the argc/argv arguments\n int argc = 1;\n const auto arg0 = \"dummy\";\n char* argv0 = const_cast(arg0);\n char** argv = &argv0;\n\n internal::InitGoogleMockImpl(&argc, argv);\n}\n\n} // namespace testing", "messages": null, "tools": null} {"id": "7866d90d9b1a567d", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/basic_json__nullptr_t.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 297, "sha256": "d7beef232947277ce87a6ffe778ee48459490ac92ca8a34c8406a9fbef1b14e1", "text": "#include \n#include \n\nusing json = nlohmann::json;\n\nint main()\n{\n // implicitly create a JSON null value\n json j1;\n\n // explicitly create a JSON null value\n json j2(nullptr);\n\n // serialize the JSON null value\n std::cout << j1 << '\\n' << j2 << '\\n';\n}", "messages": null, "tools": null} {"id": "786aa7310839f1f2", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/node/ssr/runtime/__tests__/fixtures/worker.invoke.mjs", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 1120, "sha256": "ac7a6d0ea91c50f6236122591db54925a7a05e9a16f6894e624be421d3d1186c", "text": "// @ts-check\n\nimport { BroadcastChannel, parentPort } from 'node:worker_threads'\nimport {\n ESModulesEvaluator,\n ModuleRunner,\n createNodeImportMeta,\n} from 'vite/module-runner'\nimport { createBirpc } from 'birpc'\n\nif (!parentPort) {\n throw new Error('File \"worker.js\" must be run in a worker thread')\n}\n\n/** @type {import('worker_threads').MessagePort} */\nconst pPort = parentPort\n\n/** @type {import('birpc').BirpcReturn<{ invoke: (data: any) => any }>} */\nconst rpc = createBirpc(\n {},\n {\n post: (data) => pPort.postMessage(data),\n on: (data) => pPort.on('message', data),\n },\n)\n\nconst runner = new ModuleRunner(\n {\n transport: {\n invoke(data) {\n return rpc.invoke(data)\n },\n },\n createImportMeta: createNodeImportMeta,\n hmr: false,\n },\n new ESModulesEvaluator(),\n)\n\nconst channel = new BroadcastChannel('vite-worker:invoke')\nchannel.onmessage = async (message) => {\n try {\n const mod = await runner.import(message.data.id)\n channel.postMessage({ result: mod.default })\n } catch (e) {\n channel.postMessage({ error: e.stack })\n }\n}\nparentPort.postMessage('ready')", "messages": null, "tools": null} {"id": "79086b88dae73f1c", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/swap__array_t.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 443, "sha256": "06b1606c46d7f70fcbd610989d18cbfb8cab059c9d848a62cec14030b3e4e797", "text": "#include \n#include \n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value\n json value = {{\"array\", {1, 2, 3, 4}}};\n\n // create an array_t\n json::array_t array = {\"Snap\", \"Crackle\", \"Pop\"};\n\n // swap the array stored in the JSON value\n value[\"array\"].swap(array);\n\n // output the values\n std::cout << \"value = \" << value << '\\n';\n std::cout << \"array = \" << array << '\\n';\n}", "messages": null, "tools": null} {"id": "794f1e73eab51eac", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/abi/config/config.hpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 940, "sha256": "dfec95b2bed82269127db0cd0abbccb4960ecadbbd5c2f81e6439b83e8e87d73", "text": "// __ _____ _____ _____\n// __| | __| | | | JSON for Modern C++ (supporting code)\n// | | |__ | | | | | | version 3.12.0\n// |_____|_____|_____|_|___| https://github.com/nlohmann/json\n//\n// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann \n// SPDX-License-Identifier: MIT\n\n#pragma once\n\n#include \"doctest.h\"\n\n#include \n#include \n#include \n\n#define STRINGIZE_EX(x) #x\n#define STRINGIZE(x) STRINGIZE_EX(x)\n\ntemplate\nstd::string namespace_name(std::string ns, T* /*unused*/ = nullptr) // NOLINT(performance-unnecessary-value-param)\n{\n#if DOCTEST_MSVC && !DOCTEST_CLANG\n ns = __FUNCSIG__;\n#elif !DOCTEST_CLANG\n ns = __PRETTY_FUNCTION__;\n#endif\n std::smatch m;\n\n // extract the true namespace name from the function signature\n CAPTURE(ns);\n CHECK(std::regex_search(ns, m, std::regex(\"nlohmann(::[a-zA-Z0-9_]+)*::basic_json\")));\n\n return m.str();\n}", "messages": null, "tools": null} {"id": "7a421f4c1450f85c", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/thirdparty/Fuzzer/test/AbsNegAndConstant64Test.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 620, "sha256": "e9ab7df8bd2d886a75a37b2ef93f516f6d856a9e4a363f585632e24cc5f7f715", "text": "// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n\n// abs(x) < 0 and y == Const puzzle, 64-bit variant.\n#include \n#include \n#include \n#include \n#include \n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {\n if (Size < 16) return 0;\n int64_t x;\n uint64_t y;\n memcpy(&x, Data, sizeof(x));\n memcpy(&y, Data + sizeof(x), sizeof(y));\n if (labs(x) < 0 && y == 0xbaddcafedeadbeefUL) {\n printf(\"BINGO; Found the target, exiting; x = 0x%lx y 0x%lx\\n\", x, y);\n exit(1);\n }\n return 0;\n}", "messages": null, "tools": null} {"id": "7a7a497f51fc035c", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/json_pointer__back.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 420, "sha256": "126c41f2769c012fc7cafdbe7982c23ba678b0b3da73ad5f20ce5f933e4d64d6", "text": "#include \n#include \n\nusing json = nlohmann::json;\n\nint main()\n{\n // different JSON Pointers\n json::json_pointer ptr1(\"/foo\");\n json::json_pointer ptr2(\"/foo/0\");\n\n // call empty()\n std::cout << \"last reference token of \\\"\" << ptr1 << \"\\\" is \\\"\" << ptr1.back() << \"\\\"\\n\"\n << \"last reference token of \\\"\" << ptr2 << \"\\\" is \\\"\" << ptr2.back() << \"\\\"\" << std::endl;\n}", "messages": null, "tools": null} {"id": "7aac3954a2332fe5", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/api/basic_json/std_formatter.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 2346, "sha256": "1a10bbcb64f6803a005761aac67c4284f2b3294505da25ab9131642a45033503", "text": "# std::formatter\n\n```cpp\nnamespace std {\n template <>\n struct formatter;\n}\n```\n\nSpecialization to make JSON values formattable with [`std::format`](https://en.cppreference.com/w/cpp/utility/format/format)\n(and the other members of C++20's `` header, such as `std::format_to`).\n\nA subset of the [standard format spec grammar](https://en.cppreference.com/w/cpp/utility/format/spec) is\nsupported, repurposed for JSON pretty-printing; any other spec component (sign, the `0` flag, precision,\n`L`, a dynamic width such as `#!cpp \"{:{}}\"`, or a trailing type character) throws\n[`std::format_error`](https://en.cppreference.com/w/cpp/utility/format/format_error):\n\n- `#!cpp \"{}\"` serializes the value the same way as [`dump()`](dump.md) (compact, no whitespace).\n- `#!cpp \"{:#}\"` (\"alternate form\") serializes the value the same way as `#!cpp dump(4)` (pretty-printed\n with an indent of 4).\n- A width, with or without `#!cpp \"#\"` (e.g. `#!cpp \"{:2}\"` or `#!cpp \"{:#2}\"`), serializes the value the\n same way as `#!cpp dump(width)` — a width on its own implies pretty-printing, since an indent size has\n no meaning for compact output.\n- `fill-and-align` (e.g. `#!cpp \"{:.>#}\"` or `#!cpp \"{:.>3}\"`) picks a custom indent character, the same\n way as `#!cpp dump(indent, indent_char)`. The alignment direction itself (`#!cpp '<'`, `#!cpp '>'`,\n `#!cpp '^'`) has no separate meaning for JSON values — only the fill character before it is used, and\n any of the three directions is accepted.\n\nThis specialization is only available for `#!cpp char`-based JSON values and only if the standard library\nprovides ``, controlled by the [`JSON_HAS_STD_FORMAT`](../macros/json_has_std_format.md) macro.\n\n## Examples\n\n??? example\n\n The example shows how to format JSON values with `std::format`.\n\n ```cpp\n --8<-- \"examples/std_formatter.c++20.cpp\"\n ```\n\n Output:\n\n ```json\n --8<-- \"examples/std_formatter.c++20.output\"\n ```\n\n## See also\n\n- [dump](dump.md) - serialization\n- [operator<<(std::ostream&)](../operator_ltlt.md) - serialize to stream\n- [format_as](format_as.md) - customization point used by `fmt::format` (fmtlib)\n- [Serialization](../../features/serialization.md) - the serialization article\n\n## Version history\n\n- Added in version 3.13.0.", "messages": null, "tools": null} {"id": "7aaf3b91798e0db2", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/define/vite.config.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 1509, "sha256": "587607571e9dd6c1f76f8aaacf3a8e3669801952c19a8382c756ba35ca2702c0", "text": "import { defineConfig } from 'vite'\n\n/**\n * Plugin to test that env imports with query parameters work correctly (#20997)\n */\nfunction testEnvQueryParamsPlugin() {\n let isBuild = true\n return {\n name: 'test-env-query-params',\n configResolved(config) {\n isBuild = config.command === 'build'\n },\n transform(code, id) {\n if (\n id.includes('index.html') &&\n code.includes('__VITE_ENV_WITH_QUERY__')\n ) {\n return code.replace(\n '__VITE_ENV_WITH_QUERY__',\n JSON.stringify(isBuild ? 'data:text/javascript,' : '/@vite/env?foo'),\n )\n }\n },\n }\n}\n\nexport default defineConfig({\n plugins: [testEnvQueryParamsPlugin()],\n define: {\n __EXP__: 'false',\n __STRING__: '\"hello\"',\n __NUMBER__: 123,\n __BOOLEAN__: true,\n __UNDEFINED__: undefined,\n __OBJ__: {\n foo: 1,\n bar: {\n baz: 2,\n },\n process: {\n env: {\n SOMEVAR: '\"PROCESS MAY BE PROPERTY\"',\n },\n },\n },\n 'process.env.NODE_ENV': '\"dev\"',\n 'process.env.SOMEVAR': '\"SOMEVAR\"',\n 'process.env': {\n NODE_ENV: 'dev',\n SOMEVAR: 'SOMEVAR',\n OTHER: 'works',\n },\n $DOLLAR: 456,\n ÖUNICODE_LETTERɵ: 789,\n __VAR_NAME__: false,\n __STRINGIFIED_OBJ__: JSON.stringify({ foo: true }),\n 'import.meta.env.SOME_IDENTIFIER': '__VITE_SOME_IDENTIFIER__',\n },\n environments: {\n client: {\n define: {\n __DEFINE_IN_ENVIRONMENT__: '\"defined only in client\"',\n },\n },\n },\n})", "messages": null, "tools": null} {"id": "7afae851a21793cf", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/chunk-importmap/index.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 541, "sha256": "d225419bffcf571e586e3ac5f88f6031ccd6564b5bfe4a8f2ab07ebdc7e187e9", "text": "import './static.js'\nimport('./dynamic.js')\nimport('./direct-dynamic.css')\nimport('./dynamic2.js')\n\nimport myWorker from './worker.js?worker'\n\ndocument.querySelector('.js').textContent = 'js: ok'\n\ndocument.querySelector('.importmap').textContent = JSON.stringify(\n JSON.parse(\n document.head.querySelector('script[type=\"importmap\"]')?.textContent,\n ),\n null,\n 2,\n)\n\nconst worker = new myWorker()\nworker.postMessage('ping')\nworker.addEventListener('message', (e) => {\n document.querySelector('.worker').textContent = e.data.message\n})", "messages": null, "tools": null} {"id": "7b15264aa41e3c42", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "include/nlohmann/detail/conversions/to_chars.hpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 38586, "sha256": "693aaabf42f83ba4d61271763eb24501622c54d690faf3e0a4e22e898aaf3031", "text": "// __ _____ _____ _____\n// __| | __| | | | JSON for Modern C++\n// | | |__ | | | | | | version 3.12.0\n// |_____|_____|_____|_|___| https://github.com/nlohmann/json\n//\n// SPDX-FileCopyrightText: 2009 Florian Loitsch \n// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann \n// SPDX-License-Identifier: MIT\n\n#pragma once\n\n#include // array\n#include // signbit, isfinite\n#include // intN_t, uintN_t\n#include // memcpy, memmove\n#include // numeric_limits\n#include // conditional\n\n#include \n\nNLOHMANN_JSON_NAMESPACE_BEGIN\nnamespace detail\n{\n\n/*!\n@brief implements the Grisu2 algorithm for binary to decimal floating-point\nconversion.\n\nThis implementation is a slightly modified version of the reference\nimplementation which may be obtained from\nhttp://florian.loitsch.com/publications (bench.tar.gz).\n\nThe code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.\n\nFor a detailed description of the algorithm see:\n\n[1] Loitsch, \"Printing Floating-Point Numbers Quickly and Accurately with\n Integers\", Proceedings of the ACM SIGPLAN 2010 Conference on Programming\n Language Design and Implementation, PLDI 2010\n[2] Burger, Dybvig, \"Printing Floating-Point Numbers Quickly and Accurately\",\n Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language\n Design and Implementation, PLDI 1996\n*/\nnamespace dtoa_impl\n{\n\ntemplate\nTarget reinterpret_bits(const Source source)\n{\n static_assert(sizeof(Target) == sizeof(Source), \"size mismatch\");\n\n Target target;\n std::memcpy(&target, &source, sizeof(Source));\n return target;\n}\n\nstruct diyfp // f * 2^e\n{\n static constexpr int kPrecision = 64; // = q\n\n std::uint64_t f = 0;\n int e = 0;\n\n constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}\n\n /*!\n @brief returns x - y\n @pre x.e == y.e and x.f >= y.f\n */\n static diyfp sub(const diyfp& x, const diyfp& y) noexcept\n {\n JSON_ASSERT(x.e == y.e);\n JSON_ASSERT(x.f >= y.f);\n\n return {x.f - y.f, x.e};\n }\n\n /*!\n @brief returns x * y\n @note The result is rounded. (Only the upper q bits are returned.)\n */\n static diyfp mul(const diyfp& x, const diyfp& y) noexcept\n {\n static_assert(kPrecision == 64, \"internal error\");\n\n // Computes:\n // f = round((x.f * y.f) / 2^q)\n // e = x.e + y.e + q\n\n // Emulate the 64-bit * 64-bit multiplication:\n //\n // p = u * v\n // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)\n // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )\n // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )\n // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )\n // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)\n // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )\n // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )\n //\n // (Since Q might be larger than 2^32 - 1)\n //\n // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)\n //\n // (Q_hi + H does not overflow a 64-bit int)\n //\n // = p_lo + 2^64 p_hi\n\n const std::uint64_t u_lo = x.f & 0xFFFFFFFFu;\n const std::uint64_t u_hi = x.f >> 32u;\n const std::uint64_t v_lo = y.f & 0xFFFFFFFFu;\n const std::uint64_t v_hi = y.f >> 32u;\n\n const std::uint64_t p0 = u_lo * v_lo;\n const std::uint64_t p1 = u_lo * v_hi;\n const std::uint64_t p2 = u_hi * v_lo;\n const std::uint64_t p3 = u_hi * v_hi;\n\n const std::uint64_t p0_hi = p0 >> 32u;\n const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu;\n const std::uint64_t p1_hi = p1 >> 32u;\n const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu;\n const std::uint64_t p2_hi = p2 >> 32u;\n\n std::uint64_t Q = p0_hi + p1_lo + p2_lo;\n\n // The full product might now be computed as\n //\n // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)\n // p_lo = p0_lo + (Q << 32)\n //\n // But in this particular case here, the full p_lo is not required.\n // Effectively, we only need to add the highest bit in p_lo to p_hi (and\n // Q_hi + 1 does not overflow).\n\n Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up\n\n const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u);\n\n return {h, x.e + y.e + 64};\n }\n\n /*!\n @brief normalize x such that the significand is >= 2^(q-1)\n @pre x.f != 0\n */\n static diyfp normalize(diyfp x) noexcept\n {\n JSON_ASSERT(x.f != 0);\n\n while ((x.f >> 63u) == 0)\n {\n x.f <<= 1u;\n x.e--;\n }\n\n return x;\n }\n\n /*!\n @brief normalize x such that the result has the exponent E\n @pre e >= x.e and the upper e - x.e bits of x.f must be zero.\n */\n static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept\n {\n const int delta = x.e - target_exponent;\n\n JSON_ASSERT(delta >= 0);\n JSON_ASSERT(((x.f << delta) >> delta) == x.f);\n\n return {x.f << delta, target_exponent};\n }\n};\n\nstruct boundaries\n{\n diyfp w;\n diyfp minus;\n diyfp plus;\n};\n\n/*!\nCompute the (normalized) diyfp representing the input number 'value' and its\nboundaries.\n\n@pre value must be finite and positive\n*/\ntemplate\nboundaries compute_boundaries(FloatType value)\n{\n JSON_ASSERT(std::isfinite(value));\n JSON_ASSERT(value > 0);\n\n // Convert the IEEE representation into a diyfp.\n //\n // If v is denormal:\n // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))\n // If v is normalized:\n // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))\n\n static_assert(std::numeric_limits::is_iec559,\n \"internal error: dtoa_short requires an IEEE-754 floating-point implementation\");\n\n constexpr int kPrecision = std::numeric_limits::digits; // = p (includes the hidden bit)\n constexpr int kBias = std::numeric_limits::max_exponent - 1 + (kPrecision - 1);\n constexpr int kMinExp = 1 - kBias;\n constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1)\n\n using bits_type = typename std::conditional::type;\n\n const auto bits = static_cast(reinterpret_bits(value));\n const std::uint64_t E = bits >> (kPrecision - 1);\n const std::uint64_t F = bits & (kHiddenBit - 1);\n\n const bool is_denormal = E == 0;\n const diyfp v = is_denormal\n ? diyfp(F, kMinExp)\n : diyfp(F + kHiddenBit, static_cast(E) - kBias);\n\n // Compute the boundaries m- and m+ of the floating-point value\n // v = f * 2^e.\n //\n // Determine v- and v+, the floating-point predecessor and successor of v,\n // respectively.\n //\n // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)\n // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)\n //\n // v+ = v + 2^e\n //\n // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_\n // between m- and m+ round to v, regardless of how the input rounding\n // algorithm breaks ties.\n //\n // ---+-------------+-------------+-------------+-------------+--- (A)\n // v- m- v m+ v+\n //\n // -----------------+------+------+-------------+-------------+--- (B)\n // v- m- v m+ v+\n\n const bool lower_boundary_is_closer = F == 0 && E > 1;\n const diyfp m_plus = diyfp((2 * v.f) + 1, v.e - 1);\n const diyfp m_minus = lower_boundary_is_closer\n ? diyfp((4 * v.f) - 1, v.e - 2) // (B)\n : diyfp((2 * v.f) - 1, v.e - 1); // (A)\n\n // Determine the normalized w+ = m+.\n const diyfp w_plus = diyfp::normalize(m_plus);\n\n // Determine w- = m- such that e_(w-) = e_(w+).\n const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);\n\n return {diyfp::normalize(v), w_minus, w_plus};\n}\n\n// Given normalized diyfp w, Grisu needs to find a (normalized) cached\n// power-of-ten c, such that the exponent of the product c * w = f * 2^e lies\n// within a certain range [alpha, gamma] (Definition 3.2 from [1])\n//\n// alpha <= e = e_c + e_w + q <= gamma\n//\n// or\n//\n// f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q\n// <= f_c * f_w * 2^gamma\n//\n// Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies\n//\n// 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma\n//\n// or\n//\n// 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)\n//\n// The choice of (alpha,gamma) determines the size of the table and the form of\n// the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well\n// in practice:\n//\n// The idea is to cut the number c * w = f * 2^e into two parts, which can be\n// processed independently: An integral part p1, and a fractional part p2:\n//\n// f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e\n// = (f div 2^-e) + (f mod 2^-e) * 2^e\n// = p1 + p2 * 2^e\n//\n// The conversion of p1 into decimal form requires a series of divisions and\n// modulos by (a power of) 10. These operations are faster for 32-bit than for\n// 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be\n// achieved by choosing\n//\n// -e >= 32 or e <= -32 := gamma\n//\n// In order to convert the fractional part\n//\n// p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...\n//\n// into decimal form, the fraction is repeatedly multiplied by 10 and the digits\n// d[-i] are extracted in order:\n//\n// (10 * p2) div 2^-e = d[-1]\n// (10 * p2) mod 2^-e = d[-2] / 10^1 + ...\n//\n// The multiplication by 10 must not overflow. It is sufficient to choose\n//\n// 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.\n//\n// Since p2 = f mod 2^-e < 2^-e,\n//\n// -e <= 60 or e >= -60 := alpha\n\nconstexpr int kAlpha = -60;\nconstexpr int kGamma = -32;\n\nstruct cached_power // c = f * 2^e ~= 10^k\n{\n std::uint64_t f;\n int e;\n int k;\n};\n\n/*!\nFor a normalized diyfp w = f * 2^e, this function returns a (normalized) cached\npower-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c\nsatisfies (Definition 3.2 from [1])\n\n alpha <= e_c + e + q <= gamma.\n*/\ninline cached_power get_cached_power_for_binary_exponent(int e)\n{\n // Now\n //\n // alpha <= e_c + e + q <= gamma (1)\n // ==> f_c * 2^alpha <= c * 2^e * 2^q\n //\n // and since the c's are normalized, 2^(q-1) <= f_c,\n //\n // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)\n // ==> 2^(alpha - e - 1) <= c\n //\n // If c were an exact power of ten, i.e. c = 10^k, one may determine k as\n //\n // k = ceil( log_10( 2^(alpha - e - 1) ) )\n // = ceil( (alpha - e - 1) * log_10(2) )\n //\n // From the paper:\n // \"In theory the result of the procedure could be wrong since c is rounded,\n // and the computation itself is approximated [...]. In practice, however,\n // this simple function is sufficient.\"\n //\n // For IEEE double precision floating-point numbers converted into\n // normalized diyfp's w = f * 2^e, with q = 64,\n //\n // e >= -1022 (min IEEE exponent)\n // -52 (p - 1)\n // -52 (p - 1, possibly normalize denormal IEEE numbers)\n // -11 (normalize the diyfp)\n // = -1137\n //\n // and\n //\n // e <= +1023 (max IEEE exponent)\n // -52 (p - 1)\n // -11 (normalize the diyfp)\n // = 960\n //\n // This binary exponent range [-1137,960] results in a decimal exponent\n // range [-307,324]. One does not need to store a cached power for each\n // k in this range. For each such k it suffices to find a cached power\n // such that the exponent of the product lies in [alpha,gamma].\n // This implies that the difference of the decimal exponents of adjacent\n // table entries must be less than or equal to\n //\n // floor( (gamma - alpha) * log_10(2) ) = 8.\n //\n // (A smaller distance gamma-alpha would require a larger table.)\n\n // NB:\n // Actually, this function returns c, such that -60 <= e_c + e + 64 <= -34.\n\n constexpr int kCachedPowersMinDecExp = -300;\n constexpr int kCachedPowersDecStep = 8;\n\n static constexpr std::array kCachedPowers =\n {\n {\n { 0xAB70FE17C79AC6CA, -1060, -300 },\n { 0xFF77B1FCBEBCDC4F, -1034, -292 },\n { 0xBE5691EF416BD60C, -1007, -284 },\n { 0x8DD01FAD907FFC3C, -980, -276 },\n { 0xD3515C2831559A83, -954, -268 },\n { 0x9D71AC8FADA6C9B5, -927, -260 },\n { 0xEA9C227723EE8BCB, -901, -252 },\n { 0xAECC49914078536D, -874, -244 },\n { 0x823C12795DB6CE57, -847, -236 },\n { 0xC21094364DFB5637, -821, -228 },\n { 0x9096EA6F3848984F, -794, -220 },\n { 0xD77485CB25823AC7, -768, -212 },\n { 0xA086CFCD97BF97F4, -741, -204 },\n { 0xEF340A98172AACE5, -715, -196 },\n { 0xB23867FB2A35B28E, -688, -188 },\n { 0x84C8D4DFD2C63F3B, -661, -180 },\n { 0xC5DD44271AD3CDBA, -635, -172 },\n { 0x936B9FCEBB25C996, -608, -164 },\n { 0xDBAC6C247D62A584, -582, -156 },\n { 0xA3AB66580D5FDAF6, -555, -148 },\n { 0xF3E2F893DEC3F126, -529, -140 },\n { 0xB5B5ADA8AAFF80B8, -502, -132 },\n { 0x87625F056C7C4A8B, -475, -124 },\n { 0xC9BCFF6034C13053, -449, -116 },\n { 0x964E858C91BA2655, -422, -108 },\n { 0xDFF9772470297EBD, -396, -100 },\n { 0xA6DFBD9FB8E5B88F, -369, -92 },\n { 0xF8A95FCF88747D94, -343, -84 },\n { 0xB94470938FA89BCF, -316, -76 },\n { 0x8A08F0F8BF0F156B, -289, -68 },\n { 0xCDB02555653131B6, -263, -60 },\n { 0x993FE2C6D07B7FAC, -236, -52 },\n { 0xE45C10C42A2B3B06, -210, -44 },\n { 0xAA242499697392D3, -183, -36 },\n { 0xFD87B5F28300CA0E, -157, -28 },\n { 0xBCE5086492111AEB, -130, -20 },\n { 0x8CBCCC096F5088CC, -103, -12 },\n { 0xD1B71758E219652C, -77, -4 },\n { 0x9C40000000000000, -50, 4 },\n { 0xE8D4A51000000000, -24, 12 },\n { 0xAD78EBC5AC620000, 3, 20 },\n { 0x813F3978F8940984, 30, 28 },\n { 0xC097CE7BC90715B3, 56, 36 },\n { 0x8F7E32CE7BEA5C70, 83, 44 },\n { 0xD5D238A4ABE98068, 109, 52 },\n { 0x9F4F2726179A2245, 136, 60 },\n { 0xED63A231D4C4FB27, 162, 68 },\n { 0xB0DE65388CC8ADA8, 189, 76 },\n { 0x83C7088E1AAB65DB, 216, 84 },\n { 0xC45D1DF942711D9A, 242, 92 },\n { 0x924D692CA61BE758, 269, 100 },\n { 0xDA01EE641A708DEA, 295, 108 },\n { 0xA26DA3999AEF774A, 322, 116 },\n { 0xF209787BB47D6B85, 348, 124 },\n { 0xB454E4A179DD1877, 375, 132 },\n { 0x865B86925B9BC5C2, 402, 140 },\n { 0xC83553C5C8965D3D, 428, 148 },\n { 0x952AB45CFA97A0B3, 455, 156 },\n { 0xDE469FBD99A05FE3, 481, 164 },\n { 0xA59BC234DB398C25, 508, 172 },\n { 0xF6C69A72A3989F5C, 534, 180 },\n { 0xB7DCBF5354E9BECE, 561, 188 },\n { 0x88FCF317F22241E2, 588, 196 },\n { 0xCC20CE9BD35C78A5, 614, 204 },\n { 0x98165AF37B2153DF, 641, 212 },\n { 0xE2A0B5DC971F303A, 667, 220 },\n { 0xA8D9D1535CE3B396, 694, 228 },\n { 0xFB9B7CD9A4A7443C, 720, 236 },\n { 0xBB764C4CA7A44410, 747, 244 },\n { 0x8BAB8EEFB6409C1A, 774, 252 },\n { 0xD01FEF10A657842C, 800, 260 },\n { 0x9B10A4E5E9913129, 827, 268 },\n { 0xE7109BFBA19C0C9D, 853, 276 },\n { 0xAC2820D9623BF429, 880, 284 },\n { 0x80444B5E7AA7CF85, 907, 292 },\n { 0xBF21E44003ACDD2D, 933, 300 },\n { 0x8E679C2F5E44FF8F, 960, 308 },\n { 0xD433179D9C8CB841, 986, 316 },\n { 0x9E19DB92B4E31BA9, 1013, 324 },\n }\n };\n\n // This computation gives exactly the same results for k as\n // k = ceil((kAlpha - e - 1) * 0.30102999566398114)\n // for |e| <= 1500, but doesn't require floating-point operations.\n // NB: log_10(2) ~= 78913 / 2^18\n JSON_ASSERT(e >= -1500);\n JSON_ASSERT(e <= 1500);\n const int f = kAlpha - e - 1;\n const int k = ((f * 78913) / (1 << 18)) + static_cast(f > 0);\n\n const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;\n JSON_ASSERT(index >= 0);\n JSON_ASSERT(static_cast(index) < kCachedPowers.size());\n\n const cached_power cached = kCachedPowers[static_cast(index)];\n JSON_ASSERT(kAlpha <= cached.e + e + 64);\n JSON_ASSERT(kGamma >= cached.e + e + 64);\n\n return cached;\n}\n\n/*!\nFor n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.\nFor n == 0, returns 1 and sets pow10 := 1.\n*/\ninline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10)\n{\n // LCOV_EXCL_START\n if (n >= 1000000000)\n {\n pow10 = 1000000000;\n return 10;\n }\n // LCOV_EXCL_STOP\n if (n >= 100000000)\n {\n pow10 = 100000000;\n return 9;\n }\n if (n >= 10000000)\n {\n pow10 = 10000000;\n return 8;\n }\n if (n >= 1000000)\n {\n pow10 = 1000000;\n return 7;\n }\n if (n >= 100000)\n {\n pow10 = 100000;\n return 6;\n }\n if (n >= 10000)\n {\n pow10 = 10000;\n return 5;\n }\n if (n >= 1000)\n {\n pow10 = 1000;\n return 4;\n }\n if (n >= 100)\n {\n pow10 = 100;\n return 3;\n }\n if (n >= 10)\n {\n pow10 = 10;\n return 2;\n }\n\n pow10 = 1;\n return 1;\n}\n\ninline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta,\n std::uint64_t rest, std::uint64_t ten_k)\n{\n JSON_ASSERT(len >= 1);\n JSON_ASSERT(dist <= delta);\n JSON_ASSERT(rest <= delta);\n JSON_ASSERT(ten_k > 0);\n\n // <--------------------------- delta ---->\n // <---- dist --------->\n // --------------[------------------+-------------------]--------------\n // M- w M+\n //\n // ten_k\n // <------>\n // <---- rest ---->\n // --------------[------------------+----+--------------]--------------\n // w V\n // = buf * 10^k\n //\n // ten_k represents a unit-in-the-last-place in the decimal representation\n // stored in buf.\n // Decrement buf by ten_k while this takes buf closer to w.\n\n // The tests are written in this order to avoid overflow in unsigned\n // integer arithmetic.\n\n while (rest < dist\n && delta - rest >= ten_k\n && (rest + ten_k < dist || dist - rest > rest + ten_k - dist))\n {\n JSON_ASSERT(buf[len - 1] != '0');\n buf[len - 1]--;\n rest += ten_k;\n }\n}\n\n/*!\nGenerates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.\nM- and M+ must be normalized and share the same exponent -60 <= e <= -32.\n*/\ninline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,\n diyfp M_minus, diyfp w, diyfp M_plus)\n{\n static_assert(kAlpha >= -60, \"internal error\");\n static_assert(kGamma <= -32, \"internal error\");\n\n // Generates the digits (and the exponent) of a decimal floating-point\n // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's\n // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.\n //\n // <--------------------------- delta ---->\n // <---- dist --------->\n // --------------[------------------+-------------------]--------------\n // M- w M+\n //\n // Grisu2 generates the digits of M+ from left to right and stops as soon as\n // V is in [M-,M+].\n\n JSON_ASSERT(M_plus.e >= kAlpha);\n JSON_ASSERT(M_plus.e <= kGamma);\n\n std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)\n std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)\n\n // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):\n //\n // M+ = f * 2^e\n // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e\n // = ((p1 ) * 2^-e + (p2 )) * 2^e\n // = p1 + p2 * 2^e\n\n const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e);\n\n auto p1 = static_cast(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.)\n std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e\n\n // 1)\n //\n // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]\n\n JSON_ASSERT(p1 > 0);\n\n std::uint32_t pow10{};\n const int k = find_largest_pow10(p1, pow10);\n\n // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)\n //\n // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))\n // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))\n //\n // M+ = p1 + p2 * 2^e\n // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e\n // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e\n // = d[k-1] * 10^(k-1) + ( rest) * 2^e\n //\n // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)\n //\n // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]\n //\n // but stop as soon as\n //\n // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e\n\n int n = k;\n while (n > 0)\n {\n // Invariants:\n // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)\n // pow10 = 10^(n-1) <= p1 < 10^n\n //\n const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)\n const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)\n //\n // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e\n // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)\n //\n JSON_ASSERT(d <= 9);\n buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d\n //\n // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)\n //\n p1 = r;\n n--;\n //\n // M+ = buffer * 10^n + (p1 + p2 * 2^e)\n // pow10 = 10^n\n //\n\n // Now check if enough digits have been generated.\n // Compute\n //\n // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e\n //\n // Note:\n // Since rest and delta share the same exponent e, it suffices to\n // compare the significands.\n const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2;\n if (rest <= delta)\n {\n // V = buffer * 10^n, with M- <= V <= M+.\n\n decimal_exponent += n;\n\n // We may now just stop. But instead, it looks as if the buffer\n // could be decremented to bring V closer to w.\n //\n // pow10 = 10^n is now 1 ulp in the decimal representation V.\n // The rounding procedure works with diyfp's with an implicit\n // exponent of e.\n //\n // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e\n //\n const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e;\n grisu2_round(buffer, length, dist, delta, rest, ten_n);\n\n return;\n }\n\n pow10 /= 10;\n //\n // pow10 = 10^(n-1) <= p1 < 10^n\n // Invariants restored.\n }\n\n // 2)\n //\n // The digits of the integral part have been generated:\n //\n // M+ = d[k-1]...d[1]d[0] + p2 * 2^e\n // = buffer + p2 * 2^e\n //\n // Now generate the digits of the fractional part p2 * 2^e.\n //\n // Note:\n // No decimal point is generated: the exponent is adjusted instead.\n //\n // p2 actually represents the fraction\n //\n // p2 * 2^e\n // = p2 / 2^-e\n // = d[-1] / 10^1 + d[-2] / 10^2 + ...\n //\n // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)\n //\n // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m\n // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)\n //\n // using\n //\n // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)\n // = ( d) * 2^-e + ( r)\n //\n // or\n // 10^m * p2 * 2^e = d + r * 2^e\n //\n // i.e.\n //\n // M+ = buffer + p2 * 2^e\n // = buffer + 10^-m * (d + r * 2^e)\n // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e\n //\n // and stop as soon as 10^-m * r * 2^e <= delta * 2^e\n\n JSON_ASSERT(p2 > delta);\n\n int m = 0;\n for (;;)\n {\n // Invariant:\n // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e\n // = buffer * 10^-m + 10^-m * (p2 ) * 2^e\n // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e\n // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e\n //\n JSON_ASSERT(p2 <= (std::numeric_limits::max)() / 10);\n p2 *= 10;\n const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e\n const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e\n //\n // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e\n // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))\n // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e\n //\n JSON_ASSERT(d <= 9);\n buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d\n //\n // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e\n //\n p2 = r;\n m++;\n //\n // M+ = buffer * 10^-m + 10^-m * p2 * 2^e\n // Invariant restored.\n\n // Check if enough digits have been generated.\n //\n // 10^-m * p2 * 2^e <= delta * 2^e\n // p2 * 2^e <= 10^m * delta * 2^e\n // p2 <= 10^m * delta\n delta *= 10;\n dist *= 10;\n if (p2 <= delta)\n {\n break;\n }\n }\n\n // V = buffer * 10^-m, with M- <= V <= M+.\n\n decimal_exponent -= m;\n\n // 1 ulp in the decimal representation is now 10^-m.\n // Since delta and dist are now scaled by 10^m, we need to do the\n // same with ulp in order to keep the units in sync.\n //\n // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e\n //\n const std::uint64_t ten_m = one.f;\n grisu2_round(buffer, length, dist, delta, p2, ten_m);\n\n // By construction this algorithm generates the shortest possible decimal\n // number (Loitsch, Theorem 6.2) which rounds back to w.\n // For an input number of precision p, at least\n //\n // N = 1 + ceil(p * log_10(2))\n //\n // decimal digits are sufficient to identify all binary floating-point\n // numbers (Matula, \"In-and-Out conversions\").\n // This implies that the algorithm does not produce more than N decimal\n // digits.\n //\n // N = 17 for p = 53 (IEEE double precision)\n // N = 9 for p = 24 (IEEE single precision)\n}\n\n/*!\nv = buf * 10^decimal_exponent\nlen is the length of the buffer (number of decimal digits)\nThe buffer must be large enough, i.e. >= max_digits10.\n*/\nJSON_HEDLEY_NON_NULL(1)\ninline void grisu2(char* buf, int& len, int& decimal_exponent,\n diyfp m_minus, diyfp v, diyfp m_plus)\n{\n JSON_ASSERT(m_plus.e == m_minus.e);\n JSON_ASSERT(m_plus.e == v.e);\n\n // --------(-----------------------+-----------------------)-------- (A)\n // m- v m+\n //\n // --------------------(-----------+-----------------------)-------- (B)\n // m- v m+\n //\n // First scale v (and m- and m+) such that the exponent is in the range\n // [alpha, gamma].\n\n const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);\n\n const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k\n\n // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]\n const diyfp w = diyfp::mul(v, c_minus_k);\n const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);\n const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);\n\n // ----(---+---)---------------(---+---)---------------(---+---)----\n // w- w w+\n // = c*m- = c*v = c*m+\n //\n // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and\n // w+ are now off by a small amount.\n // In fact:\n //\n // w - v * 10^k < 1 ulp\n //\n // To account for this inaccuracy, add resp. subtract 1 ulp.\n //\n // --------+---[---------------(---+---)---------------]---+--------\n // w- M- w M+ w+\n //\n // Now any number in [M-, M+] (bounds included) will round to w when input,\n // regardless of how the input rounding algorithm breaks ties.\n //\n // And digit_gen generates the shortest possible such number in [M-, M+].\n // Note that this does not mean that Grisu2 always generates the shortest\n // possible number in the interval (m-, m+).\n const diyfp M_minus(w_minus.f + 1, w_minus.e);\n const diyfp M_plus (w_plus.f - 1, w_plus.e );\n\n decimal_exponent = -cached.k; // = -(-k) = k\n\n grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);\n}\n\n/*!\nv = buf * 10^decimal_exponent\nlen is the length of the buffer (number of decimal digits)\nThe buffer must be large enough, i.e. >= max_digits10.\n*/\ntemplate\nJSON_HEDLEY_NON_NULL(1)\nvoid grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)\n{\n static_assert(diyfp::kPrecision >= std::numeric_limits::digits + 3,\n \"internal error: not enough precision\");\n\n JSON_ASSERT(std::isfinite(value));\n JSON_ASSERT(value > 0);\n\n // If the neighbors (and boundaries) of 'value' are always computed for double-precision\n // numbers, all float's can be recovered using strtod (and strtof). However, the resulting\n // decimal representations are not exactly \"short\".\n //\n // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)\n // says \"value is converted to a string as if by std::sprintf in the default (\"C\") locale\"\n // and since sprintf promotes floats to doubles, I think this is exactly what 'std::to_chars'\n // does.\n // On the other hand, the documentation for 'std::to_chars' requires that \"parsing the\n // representation using the corresponding std::from_chars function recovers value exactly\". That\n // indicates that single precision floating-point numbers should be recovered using\n // 'std::strtof'.\n //\n // NB: If the neighbors are computed for single-precision numbers, there is a single float\n // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision\n // value is off by 1 ulp.\n#if 0 // NOLINT(readability-avoid-unconditional-preprocessor-if)\n const boundaries w = compute_boundaries(static_cast(value));\n#else\n const boundaries w = compute_boundaries(value);\n#endif\n\n grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);\n}\n\n/*!\n@brief appends a decimal representation of e to buf\n@return a pointer to the element following the exponent.\n@pre -1000 < e < 1000\n*/\nJSON_HEDLEY_NON_NULL(1)\nJSON_HEDLEY_RETURNS_NON_NULL\ninline char* append_exponent(char* buf, int e)\n{\n JSON_ASSERT(e > -1000);\n JSON_ASSERT(e < 1000);\n\n if (e < 0)\n {\n e = -e;\n *buf++ = '-';\n }\n else\n {\n *buf++ = '+';\n }\n\n auto k = static_cast(e);\n if (k < 10)\n {\n // Always print at least two digits in the exponent.\n // This is for compatibility with printf(\"%g\").\n *buf++ = '0';\n *buf++ = static_cast('0' + k);\n }\n else if (k < 100)\n {\n *buf++ = static_cast('0' + (k / 10));\n k %= 10;\n *buf++ = static_cast('0' + k);\n }\n else\n {\n *buf++ = static_cast('0' + (k / 100));\n k %= 100;\n *buf++ = static_cast('0' + (k / 10));\n k %= 10;\n *buf++ = static_cast('0' + k);\n }\n\n return buf;\n}\n\n/*!\n@brief prettify v = buf * 10^decimal_exponent\n\nIf v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point\nnotation. Otherwise it will be printed in exponential notation.\n\n@pre min_exp < 0\n@pre max_exp > 0\n*/\nJSON_HEDLEY_NON_NULL(1)\nJSON_HEDLEY_RETURNS_NON_NULL\ninline char* format_buffer(char* buf, int len, int decimal_exponent,\n int min_exp, int max_exp)\n{\n JSON_ASSERT(min_exp < 0);\n JSON_ASSERT(max_exp > 0);\n\n const int k = len;\n const int n = len + decimal_exponent;\n\n // v = buf * 10^(n-k)\n // k is the length of the buffer (number of decimal digits)\n // n is the position of the decimal point relative to the start of the buffer.\n\n if (k <= n && n <= max_exp)\n {\n // digits[000]\n // len <= max_exp + 2\n\n std::memset(buf + k, '0', static_cast(n) - static_cast(k));\n // Make it look like a floating-point number (#362, #378)\n buf[n + 0] = '.';\n buf[n + 1] = '0';\n return buf + (static_cast(n) + 2);\n }\n\n if (0 < n && n <= max_exp)\n {\n // dig.its\n // len <= max_digits10 + 1\n\n JSON_ASSERT(k > n);\n\n std::memmove(buf + (static_cast(n) + 1), buf + n, static_cast(k) - static_cast(n));\n buf[n] = '.';\n return buf + (static_cast(k) + 1U);\n }\n\n if (min_exp < n && n <= 0)\n {\n // 0.[000]digits\n // len <= 2 + (-min_exp - 1) + max_digits10\n\n std::memmove(buf + (2 + static_cast(-n)), buf, static_cast(k));\n buf[0] = '0';\n buf[1] = '.';\n std::memset(buf + 2, '0', static_cast(-n));\n return buf + (2U + static_cast(-n) + static_cast(k));\n }\n\n if (k == 1)\n {\n // dE+123\n // len <= 1 + 5\n\n buf += 1;\n }\n else\n {\n // d.igitsE+123\n // len <= max_digits10 + 1 + 5\n\n std::memmove(buf + 2, buf + 1, static_cast(k) - 1);\n buf[1] = '.';\n buf += 1 + static_cast(k);\n }\n\n *buf++ = 'e';\n return append_exponent(buf, n - 1);\n}\n\n} // namespace dtoa_impl\n\n/*!\n@brief generates a decimal representation of the floating-point number value in [first, last).\n\nThe format of the resulting decimal representation is similar to printf's %g\nformat. Returns an iterator pointing past-the-end of the decimal representation.\n\n@note The input number must be finite, i.e. NaN's and Inf's are not supported.\n@note The buffer must be large enough.\n@note The result is NOT null-terminated.\n*/\ntemplate\nJSON_HEDLEY_NON_NULL(1, 2)\nJSON_HEDLEY_RETURNS_NON_NULL\nchar* to_chars(char* first, const char* last, FloatType value)\n{\n static_cast(last); // maybe unused - fix warning\n JSON_ASSERT(std::isfinite(value));\n\n // Use signbit(value) instead of (value < 0) since signbit works for -0.\n if (std::signbit(value))\n {\n value = -value;\n *first++ = '-';\n }\n\n#ifdef __GNUC__\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wfloat-equal\"\n#endif\n if (value == 0) // +-0\n {\n *first++ = '0';\n // Make it look like a floating-point number (#362, #378)\n *first++ = '.';\n *first++ = '0';\n return first;\n }\n#ifdef __GNUC__\n#pragma GCC diagnostic pop\n#endif\n\n JSON_ASSERT(last - first >= std::numeric_limits::max_digits10);\n\n // Compute v = buffer * 10^decimal_exponent.\n // The decimal digits are stored in the buffer, which needs to be interpreted\n // as an unsigned decimal integer.\n // len is the length of the buffer, i.e., the number of decimal digits.\n int len = 0;\n int decimal_exponent = 0;\n dtoa_impl::grisu2(first, len, decimal_exponent, value);\n\n JSON_ASSERT(len <= std::numeric_limits::max_digits10);\n\n // Format the buffer like printf(\"%.*g\", prec, value)\n constexpr int kMinExp = -4;\n // Use digits10 here to increase compatibility with version 2.\n constexpr int kMaxExp = std::numeric_limits::digits10;\n\n JSON_ASSERT(last - first >= kMaxExp + 2);\n JSON_ASSERT(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits::max_digits10);\n JSON_ASSERT(last - first >= std::numeric_limits::max_digits10 + 6);\n\n return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);\n}\n\n} // namespace detail\nNLOHMANN_JSON_NAMESPACE_END", "messages": null, "tools": null} {"id": "7b79a35c15a85358", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/thirdparty/Fuzzer/FuzzerExtFunctionsWeakAlias.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 1804, "sha256": "61a8008234c60a15944ba402423baaa4e5fb07dceada8a09ab318d9adf17835c", "text": "//===- FuzzerExtFunctionsWeakAlias.cpp - Interface to external functions --===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n// Implementation using weak aliases. Works for Windows.\n//===----------------------------------------------------------------------===//\n#include \"FuzzerDefs.h\"\n#if LIBFUZZER_WINDOWS\n\n#include \"FuzzerExtFunctions.h\"\n#include \"FuzzerIO.h\"\n\nusing namespace fuzzer;\n\nextern \"C\" {\n// Declare these symbols as weak to allow them to be optionally defined.\n#define EXT_FUNC(NAME, RETURN_TYPE, FUNC_SIG, WARN) \\\n RETURN_TYPE NAME##Def FUNC_SIG { \\\n Printf(\"ERROR: Function \\\"%s\\\" not defined.\\n\", #NAME); \\\n exit(1); \\\n } \\\n RETURN_TYPE NAME FUNC_SIG __attribute__((weak, alias(#NAME \"Def\")));\n\n#include \"FuzzerExtFunctions.def\"\n\n#undef EXT_FUNC\n}\n\ntemplate \nstatic T *GetFnPtr(T *Fun, T *FunDef, const char *FnName, bool WarnIfMissing) {\n if (Fun == FunDef) {\n if (WarnIfMissing)\n Printf(\"WARNING: Failed to find function \\\"%s\\\".\\n\", FnName);\n return nullptr;\n }\n return Fun;\n}\n\nnamespace fuzzer {\n\nExternalFunctions::ExternalFunctions() {\n#define EXT_FUNC(NAME, RETURN_TYPE, FUNC_SIG, WARN) \\\n this->NAME = GetFnPtr(::NAME, ::NAME##Def, #NAME, WARN);\n\n#include \"FuzzerExtFunctions.def\"\n\n#undef EXT_FUNC\n}\n\n} // namespace fuzzer\n\n#endif // LIBFUZZER_WINDOWS", "messages": null, "tools": null} {"id": "7bb7cfc9381eee18", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/nlohmann_define_type_non_intrusive_with_names_explicit.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 1740, "sha256": "17f2759440b8d5996c695c45a21180392fff5e1cdbca59f0898d0908f782b8a5", "text": "#include \n#include \n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nstruct person\n{\n std::string name;\n std::string address;\n int age;\n};\n\ntemplate ::value, int> = 0>\nvoid to_json(BasicJsonType& nlohmann_json_j, const person& nlohmann_json_t)\n{\n nlohmann_json_j[\"json_name\"] = nlohmann_json_t.name;\n nlohmann_json_j[\"json_address\"] = nlohmann_json_t.address;\n nlohmann_json_j[\"json_age\"] = nlohmann_json_t.age;\n}\n\ntemplate ::value, int> = 0>\nvoid from_json(const BasicJsonType& nlohmann_json_j, person& nlohmann_json_t)\n{\n nlohmann_json_j.at(\"json_name\").get_to(nlohmann_json_t.name);\n nlohmann_json_j.at(\"json_address\").get_to(nlohmann_json_t.address);\n nlohmann_json_j.at(\"json_age\").get_to(nlohmann_json_t.age);\n}\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n\n // deserialization: json -> person\n json j2 = R\"({\"json_address\": \"742 Evergreen Terrace\", \"json_age\": 40, \"json_name\": \"Homer Simpson\"})\"_json;\n auto p2 = j2.template get();\n\n // incomplete deserialization:\n json j3 = R\"({\"json_address\": \"742 Evergreen Terrace\", \"json_name\": \"Maggie Simpson\"})\"_json;\n try\n {\n auto p3 = j3.template get();\n }\n catch (const json::exception& e)\n {\n std::cout << \"deserialization failed: \" << e.what() << std::endl;\n }\n}", "messages": null, "tools": null} {"id": "7c03eda1a619ffb6", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/reject_duplicate_keys.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 1655, "sha256": "19304d317d19fb347fa938a6d0573fb4840524409476c68a676635380a53d755", "text": "#include \n#include \n#include \n#include \n#include \n#include \n\nusing json = nlohmann::json;\n\njson parse_strict(const std::string& input)\n{\n // one key set per nesting depth, reused across sibling objects\n std::vector> keys;\n\n auto reject_duplicate_keys = [&](int depth, json::parse_event_t event, json & parsed)\n {\n if (event == json::parse_event_t::object_start)\n {\n // keys of this object are reported at depth+1 (see the event table above)\n const auto child_depth = static_cast(depth) + 1;\n if (keys.size() <= child_depth)\n {\n keys.resize(child_depth + 1);\n }\n keys[child_depth].clear();\n return true;\n }\n\n if (event == json::parse_event_t::key)\n {\n auto& seen = keys[static_cast(depth)];\n const auto& key = parsed.get_ref();\n if (!seen.insert(key).second)\n {\n throw std::runtime_error(\"duplicate JSON object key: \" + key);\n }\n return true;\n }\n\n return true;\n };\n\n return json::parse(input, reject_duplicate_keys);\n}\n\nint main()\n{\n // parsing succeeds when all keys are unique\n json j = parse_strict(R\"({\"one\": 1, \"two\": 2})\");\n std::cout << j << '\\n';\n\n // parsing throws when a key is repeated\n try\n {\n parse_strict(R\"({\"one\": 1, \"one\": 2})\");\n }\n catch (const std::exception& e)\n {\n std::cout << e.what() << '\\n';\n }\n}", "messages": null, "tools": null} {"id": "7c6654529ccb792c", "category": "code", "domain": "code", "source": "serde", "license": "MIT OR Apache-2.0", "license_url": "https://spdx.org/licenses/MIT.html", "path": "test_suite/tests/bytes/mod.rs", "lang": "rust", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/serde-rs/serde", "commit": "747814f7d5fbab872df3b02f070c165b91bde062", "collector": "tools/harvest.py"}, "chars": 1257, "sha256": "c2a61bca82664ec238a95a6a534c603f55c5718b437b6f6b0faa4dc52b6c3bee", "text": "use serde::de::{Deserializer, Error, SeqAccess, Visitor};\nuse std::fmt;\n\npub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error>\nwhere\n D: Deserializer<'de>,\n{\n deserializer.deserialize_byte_buf(ByteBufVisitor)\n}\n\nstruct ByteBufVisitor;\n\nimpl<'de> Visitor<'de> for ByteBufVisitor {\n type Value = Vec;\n\n fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\n formatter.write_str(\"byte array\")\n }\n\n fn visit_seq(self, mut visitor: V) -> Result\n where\n V: SeqAccess<'de>,\n {\n let mut values = Vec::new();\n while let Some(value) = visitor.next_element()? {\n values.push(value);\n }\n Ok(values)\n }\n\n fn visit_bytes(self, v: &[u8]) -> Result\n where\n E: Error,\n {\n Ok(v.to_vec())\n }\n\n fn visit_byte_buf(self, v: Vec) -> Result\n where\n E: Error,\n {\n Ok(v)\n }\n\n fn visit_str(self, v: &str) -> Result\n where\n E: Error,\n {\n Ok(v.as_bytes().to_vec())\n }\n\n fn visit_string(self, v: String) -> Result\n where\n E: Error,\n {\n Ok(v.into_bytes())\n }\n}", "messages": null, "tools": null} {"id": "7c945fea82f65c37", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/api/basic_json/rend.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 831, "sha256": "991a9027e0dc684ff0e67abe6432db711477784cdddbba4616639157e2f2fe11", "text": "# nlohmann::basic_json::rend\n\n```cpp\nreverse_iterator rend() noexcept;\nconst_reverse_iterator rend() const noexcept;\n```\n\nReturns an iterator to the reverse-end; that is, one before the first element. This element acts as a placeholder,\nattempting to access it results in undefined behavior.\n\n![Illustration from cppreference.com](../../images/range-rbegin-rend.svg)\n\n## Return value\n\nreverse iterator to the element following the last element\n\n## Exception safety\n\nNo-throw guarantee: this member function never throws exceptions.\n\n## Complexity\n\nConstant.\n\n## Examples\n\n??? example\n\n The following code shows an example for `rend()`.\n \n ```cpp\n --8<-- \"examples/rend.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/rend.output\"\n ```\n\n## Version history\n\n- Added in version 1.0.0.", "messages": null, "tools": null} {"id": "7cbafd522fccb55e", "category": "code", "domain": "code", "source": "ripgrep", "license": "MIT OR Unlicense", "license_url": "https://spdx.org/licenses/MIT.html", "path": "crates/ignore/src/walk.rs", "lang": "rust", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/BurntSushi/ripgrep", "commit": "3fce3b5bb0236da2df6d99672afb8a719642eca7", "collector": "tools/harvest.py"}, "chars": 93442, "sha256": "8e14a7ea89f4e0caa3d3cb18409b51e519fc489fec8dacc8142ccbe03d2096e3", "text": "use std::{\n cmp::Ordering,\n ffi::OsStr,\n fs::{self, FileType, Metadata},\n io,\n path::{Path, PathBuf},\n sync::atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrdering},\n sync::{Arc, OnceLock},\n};\n\nuse {\n crossbeam_deque::{Stealer, Worker as Deque},\n same_file::Handle,\n walkdir::WalkDir,\n};\n\nuse crate::{\n Error, PartialErrorBuilder,\n dir::{Ignore, IgnoreBuilder},\n gitignore::GitignoreBuilder,\n incremental::{IncrementalIgnore, IncrementalIgnoreOptions},\n overrides::Override,\n types::Types,\n};\n\n/// A directory entry with a possible error attached.\n///\n/// The error typically refers to a problem parsing ignore files in a\n/// particular directory.\n#[derive(Clone, Debug)]\npub struct DirEntry {\n dent: DirEntryInner,\n err: Option,\n}\n\nimpl DirEntry {\n /// The full path that this entry represents.\n pub fn path(&self) -> &Path {\n self.dent.path()\n }\n\n /// The full path that this entry represents.\n /// Analogous to [`DirEntry::path`], but moves ownership of the path.\n pub fn into_path(self) -> PathBuf {\n self.dent.into_path()\n }\n\n /// Whether this entry corresponds to a symbolic link or not.\n pub fn path_is_symlink(&self) -> bool {\n self.dent.path_is_symlink()\n }\n\n /// Returns true if and only if this entry corresponds to stdin.\n ///\n /// i.e., The entry has depth 0 and its file name is `-`.\n pub fn is_stdin(&self) -> bool {\n self.dent.is_stdin()\n }\n\n /// Return the metadata for the file that this entry points to.\n pub fn metadata(&self) -> Result {\n self.dent.metadata()\n }\n\n /// Return the file type for the file that this entry points to.\n ///\n /// This entry doesn't have a file type if it corresponds to stdin.\n pub fn file_type(&self) -> Option {\n self.dent.file_type()\n }\n\n /// Return the file name of this entry.\n ///\n /// If this entry has no file name (e.g., `/`), then the full path is\n /// returned.\n pub fn file_name(&self) -> &OsStr {\n self.dent.file_name()\n }\n\n /// Returns the depth at which this entry was created relative to the root.\n pub fn depth(&self) -> usize {\n self.dent.depth()\n }\n\n /// Returns the underlying inode number if one exists.\n ///\n /// If this entry doesn't have an inode number, then `None` is returned.\n #[cfg(unix)]\n pub fn ino(&self) -> Option {\n self.dent.ino()\n }\n\n /// Returns an error, if one exists, associated with processing this entry.\n ///\n /// An example of an error is one that occurred while parsing an ignore\n /// file. Errors related to traversing a directory tree itself are reported\n /// as part of yielding the directory entry, and not with this method.\n pub fn error(&self) -> Option<&Error> {\n self.err.as_ref()\n }\n\n /// Returns true if and only if this entry points to a directory.\n pub(crate) fn is_dir(&self) -> bool {\n self.dent.is_dir()\n }\n\n fn new_stdin() -> DirEntry {\n DirEntry { dent: DirEntryInner::Stdin, err: None }\n }\n\n fn new_walkdir(dent: walkdir::DirEntry, err: Option) -> DirEntry {\n DirEntry { dent: DirEntryInner::Walkdir(dent), err }\n }\n\n fn new_raw(dent: DirEntryRaw, err: Option) -> DirEntry {\n DirEntry { dent: DirEntryInner::Raw(dent), err }\n }\n}\n\n/// DirEntryInner is the implementation of DirEntry.\n///\n/// It specifically represents three distinct sources of directory entries:\n///\n/// 1. From the walkdir crate.\n/// 2. Special entries that represent things like stdin.\n/// 3. From a path.\n///\n/// Specifically, (3) has to essentially re-create the DirEntry implementation\n/// from WalkDir.\n#[derive(Clone, Debug)]\nenum DirEntryInner {\n Stdin,\n Walkdir(walkdir::DirEntry),\n Raw(DirEntryRaw),\n}\n\nimpl DirEntryInner {\n fn path(&self) -> &Path {\n use self::DirEntryInner::*;\n match *self {\n Stdin => Path::new(\"\"),\n Walkdir(ref x) => x.path(),\n Raw(ref x) => x.path(),\n }\n }\n\n fn into_path(self) -> PathBuf {\n use self::DirEntryInner::*;\n match self {\n Stdin => PathBuf::from(\"\"),\n Walkdir(x) => x.into_path(),\n Raw(x) => x.into_path(),\n }\n }\n\n fn path_is_symlink(&self) -> bool {\n use self::DirEntryInner::*;\n match *self {\n Stdin => false,\n Walkdir(ref x) => x.path_is_symlink(),\n Raw(ref x) => x.path_is_symlink(),\n }\n }\n\n fn is_stdin(&self) -> bool {\n match *self {\n DirEntryInner::Stdin => true,\n _ => false,\n }\n }\n\n fn metadata(&self) -> Result {\n use self::DirEntryInner::*;\n match *self {\n Stdin => {\n let err = Error::Io(io::Error::new(\n io::ErrorKind::Other,\n \" has no metadata\",\n ));\n Err(err.with_path(\"\"))\n }\n Walkdir(ref x) => x.metadata().map_err(|err| {\n Error::Io(io::Error::from(err))\n .with_depth(x.depth())\n .with_path(x.path())\n }),\n Raw(ref x) => x.metadata(),\n }\n }\n\n fn file_type(&self) -> Option {\n use self::DirEntryInner::*;\n match *self {\n Stdin => None,\n Walkdir(ref x) => Some(x.file_type()),\n Raw(ref x) => Some(x.file_type()),\n }\n }\n\n fn file_name(&self) -> &OsStr {\n use self::DirEntryInner::*;\n match *self {\n Stdin => OsStr::new(\"\"),\n Walkdir(ref x) => x.file_name(),\n Raw(ref x) => x.file_name(),\n }\n }\n\n fn depth(&self) -> usize {\n use self::DirEntryInner::*;\n match *self {\n Stdin => 0,\n Walkdir(ref x) => x.depth(),\n Raw(ref x) => x.depth(),\n }\n }\n\n #[cfg(unix)]\n fn ino(&self) -> Option {\n use self::DirEntryInner::*;\n use walkdir::DirEntryExt;\n match *self {\n Stdin => None,\n Walkdir(ref x) => Some(x.ino()),\n Raw(ref x) => Some(x.ino()),\n }\n }\n\n /// Returns true if and only if this entry points to a directory.\n fn is_dir(&self) -> bool {\n self.file_type().map(|ft| ft.is_dir()).unwrap_or(false)\n }\n}\n\n/// DirEntryRaw is essentially copied from the walkdir crate so that we can\n/// build `DirEntry`s from whole cloth in the parallel iterator.\n#[derive(Clone)]\nstruct DirEntryRaw {\n /// The path as reported by the `fs::ReadDir` iterator (even if it's a\n /// symbolic link).\n path: PathBuf,\n /// The file type. Necessary for recursive iteration, so store it.\n ty: FileType,\n /// Is set when this entry was created from a symbolic link and the user\n /// expects the iterator to follow symbolic links.\n follow_link: bool,\n /// The depth at which this entry was generated relative to the root.\n depth: usize,\n /// The underlying inode number (Unix only).\n #[cfg(unix)]\n ino: u64,\n /// The underlying metadata (Windows only). We store this on Windows\n /// because this comes for free while reading a directory.\n #[cfg(windows)]\n metadata: fs::Metadata,\n}\n\nimpl std::fmt::Debug for DirEntryRaw {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n // Leaving out FileType because it doesn't have a debug impl\n // in Rust 1.9. We could add it if we really wanted to by manually\n // querying each possibly file type. Meh. ---AG\n f.debug_struct(\"DirEntryRaw\")\n .field(\"path\", &self.path)\n .field(\"follow_link\", &self.follow_link)\n .field(\"depth\", &self.depth)\n .finish()\n }\n}\n\nimpl DirEntryRaw {\n fn path(&self) -> &Path {\n &self.path\n }\n\n fn into_path(self) -> PathBuf {\n self.path\n }\n\n fn path_is_symlink(&self) -> bool {\n self.ty.is_symlink() || self.follow_link\n }\n\n fn metadata(&self) -> Result {\n self.metadata_internal()\n }\n\n #[cfg(windows)]\n fn metadata_internal(&self) -> Result {\n if self.follow_link {\n fs::metadata(&self.path)\n } else {\n Ok(self.metadata.clone())\n }\n .map_err(|err| Error::Io(io::Error::from(err)).with_path(&self.path))\n }\n\n #[cfg(not(windows))]\n fn metadata_internal(&self) -> Result {\n if self.follow_link {\n fs::metadata(&self.path)\n } else {\n fs::symlink_metadata(&self.path)\n }\n .map_err(|err| {\n Error::Io(err).with_depth(self.depth).with_path(&self.path)\n })\n }\n\n fn file_type(&self) -> FileType {\n self.ty\n }\n\n fn file_name(&self) -> &OsStr {\n self.path.file_name().unwrap_or_else(|| self.path.as_os_str())\n }\n\n fn depth(&self) -> usize {\n self.depth\n }\n\n #[cfg(unix)]\n fn ino(&self) -> u64 {\n self.ino\n }\n\n fn from_entry(\n depth: usize,\n ent: &fs::DirEntry,\n ) -> Result {\n let ty = ent.file_type().map_err(|err| {\n let err = Error::Io(err).with_depth(depth).with_path(ent.path());\n Error::WithDepth { depth, err: Box::new(err) }\n })?;\n DirEntryRaw::from_entry_os(depth, ent, ty)\n }\n\n #[cfg(windows)]\n fn from_entry_os(\n depth: usize,\n ent: &fs::DirEntry,\n ty: fs::FileType,\n ) -> Result {\n let md = ent.metadata().map_err(|err| {\n let err = Error::Io(err).with_depth(depth).with_path(ent.path());\n Error::WithDepth { depth, err: Box::new(err) }\n })?;\n Ok(DirEntryRaw {\n path: ent.path(),\n ty,\n follow_link: false,\n depth,\n metadata: md,\n })\n }\n\n #[cfg(unix)]\n fn from_entry_os(\n depth: usize,\n ent: &fs::DirEntry,\n ty: fs::FileType,\n ) -> Result {\n use std::os::unix::fs::DirEntryExt;\n\n Ok(DirEntryRaw {\n path: ent.path(),\n ty,\n follow_link: false,\n depth,\n ino: ent.ino(),\n })\n }\n\n // Placeholder implementation to allow compiling on non-standard platforms\n // (e.g. wasm32).\n #[cfg(not(any(windows, unix)))]\n fn from_entry_os(\n depth: usize,\n ent: &fs::DirEntry,\n ty: fs::FileType,\n ) -> Result {\n Err(Error::Io(io::Error::new(\n io::ErrorKind::Other,\n \"unsupported platform\",\n )))\n }\n\n #[cfg(windows)]\n fn from_path(\n depth: usize,\n pb: PathBuf,\n link: bool,\n ) -> Result {\n let md = fs::metadata(&pb)\n .map_err(|err| Error::Io(err).with_depth(depth).with_path(&pb))?;\n Ok(DirEntryRaw {\n path: pb,\n ty: md.file_type(),\n follow_link: link,\n depth,\n metadata: md,\n })\n }\n\n #[cfg(unix)]\n fn from_path(\n depth: usize,\n pb: PathBuf,\n link: bool,\n ) -> Result {\n use std::os::unix::fs::MetadataExt;\n\n let md = fs::metadata(&pb)\n .map_err(|err| Error::Io(err).with_depth(depth).with_path(&pb))?;\n Ok(DirEntryRaw {\n path: pb,\n ty: md.file_type(),\n follow_link: link,\n depth,\n ino: md.ino(),\n })\n }\n\n // Placeholder implementation to allow compiling on non-standard platforms\n // (e.g. wasm32).\n #[cfg(not(any(windows, unix)))]\n fn from_path(\n depth: usize,\n pb: PathBuf,\n link: bool,\n ) -> Result {\n Err(Error::Io(io::Error::new(\n io::ErrorKind::Other,\n \"unsupported platform\",\n )))\n }\n}\n\n/// WalkBuilder builds a recursive directory iterator.\n///\n/// The builder supports a large number of configurable options. This includes\n/// specific glob overrides, file type matching, toggling whether hidden\n/// files are ignored or not, and of course, support for respecting gitignore\n/// files.\n///\n/// By default, all ignore files found are respected. This includes `.ignore`,\n/// `.gitignore`, `.git/info/exclude` and even your global gitignore\n/// globs, usually found in `$XDG_CONFIG_HOME/git/ignore`.\n///\n/// Some standard recursive directory options are also supported, such as\n/// limiting the recursive depth or whether to follow symbolic links (disabled\n/// by default).\n///\n/// # Ignore rules\n///\n/// There are many rules that influence whether a particular file or directory\n/// is skipped by this iterator. Those rules are documented here. Note that\n/// the rules assume a default configuration.\n///\n/// * First, glob overrides are checked. If a path matches a glob override,\n/// then matching stops. The path is then only skipped if the glob that matched\n/// the path is an ignore glob. (An override glob is a whitelist glob unless it\n/// starts with a `!`, in which case it is an ignore glob.)\n/// * Second, ignore files are checked. Ignore files currently only come from\n/// git ignore files (`.gitignore`, `.git/info/exclude` and the configured\n/// global gitignore file), plain `.ignore` files, which have the same format\n/// as gitignore files, or explicitly added ignore files. The precedence order\n/// is: `.ignore`, `.gitignore`, `.git/info/exclude`, global gitignore and\n/// finally explicitly added ignore files. Note that precedence between\n/// different types of ignore files is not impacted by the directory hierarchy;\n/// any `.ignore` file overrides all `.gitignore` files. Within each precedence\n/// level, more nested ignore files have a higher precedence than less nested\n/// ignore files.\n/// * Third, if the previous step yields an ignore match, then all matching\n/// is stopped and the path is skipped. If it yields a whitelist match, then\n/// matching continues. A whitelist match can be overridden by a later matcher.\n/// * Fourth, unless the path is a directory, the file type matcher is run on\n/// the path. As above, if it yields an ignore match, then all matching is\n/// stopped and the path is skipped. If it yields a whitelist match, then\n/// matching continues.\n/// * Fifth, if the path hasn't been whitelisted and it is hidden, then the\n/// path is skipped.\n/// * Sixth, unless the path is a directory, the size of the file is compared\n/// against the max filesize limit. If it exceeds the limit, it is skipped.\n/// * Seventh, if the path has made it this far then it is yielded in the\n/// iterator.\n#[derive(Clone)]\npub struct WalkBuilder {\n paths: Vec,\n ig_builder: IgnoreBuilder,\n max_depth: Option,\n min_depth: Option,\n max_filesize: Option,\n follow_links: bool,\n same_file_system: bool,\n sorter: Option,\n threads: usize,\n skip: Option>,\n filter: Option,\n /// The directory that gitignores should be interpreted relative to.\n ///\n /// Usually this is the directory containing the gitignore file. But in\n /// some cases, like for global gitignores or for gitignores specified\n /// explicitly, this should generally be set to the current working\n /// directory. This is only used for global gitignores or \"explicit\"\n /// gitignores.\n ///\n /// When `None`, the CWD is fetched from `std::env::current_dir()`. If\n /// that fails, then global gitignores are ignored (an error is logged).\n global_gitignores_relative_to:\n OnceLock>>,\n}\n\n#[derive(Clone)]\nenum Sorter {\n ByName(Arc Ordering + Send + Sync + 'static>),\n ByPath(Arc Ordering + Send + Sync + 'static>),\n}\n\n#[derive(Clone)]\nstruct Filter(Arc bool + Send + Sync + 'static>);\n\nimpl std::fmt::Debug for WalkBuilder {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"WalkBuilder\")\n .field(\"paths\", &self.paths)\n .field(\"ig_builder\", &self.ig_builder)\n .field(\"max_depth\", &self.max_depth)\n .field(\"min_depth\", &self.min_depth)\n .field(\"max_filesize\", &self.max_filesize)\n .field(\"follow_links\", &self.follow_links)\n .field(\"same_file_system\", &self.same_file_system)\n .field(\"sorter\", &\"<...>\")\n .field(\"threads\", &self.threads)\n .field(\"skip\", &self.skip)\n .field(\"filter\", &\"<...>\")\n .field(\n \"global_gitignores_relative_to\",\n &self.global_gitignores_relative_to,\n )\n .finish()\n }\n}\n\nimpl WalkBuilder {\n /// Create a new builder for a recursive directory iterator for the\n /// directory given.\n ///\n /// Note that if you want to traverse multiple different directories, it\n /// is better to call `add` on this builder than to create multiple\n /// `Walk` values.\n pub fn new>(path: P) -> WalkBuilder {\n WalkBuilder::from_iter([path])\n }\n\n /// Create an empty builder to which paths can be added.\n ///\n /// Note that if you call `build` on this instance before calling `add`\n /// on it, it will return exactly zero items during iteration.\n pub fn empty() -> WalkBuilder {\n WalkBuilder {\n paths: vec![],\n ig_builder: IgnoreBuilder::new(),\n max_depth: None,\n min_depth: None,\n max_filesize: None,\n follow_links: false,\n same_file_system: false,\n sorter: None,\n threads: 0,\n skip: None,\n filter: None,\n global_gitignores_relative_to: OnceLock::new(),\n }\n }\n\n /// Create a new builder for a recursive directory iterator from the\n /// sequence of paths.\n ///\n /// Note that if the iterator is empty, this is the same as\n /// `WalkBuilder::empty`.\n pub fn from_iter, I: IntoIterator>(\n paths: I,\n ) -> WalkBuilder {\n let mut builder = WalkBuilder::empty();\n for path in paths.into_iter() {\n builder.add(path);\n }\n builder\n }\n\n /// Build a new `Walk` iterator.\n pub fn build(&self) -> Walk {\n let follow_links = self.follow_links;\n let max_depth = self.max_depth;\n let min_depth = self.min_depth;\n let sorter = self.sorter.clone();\n let its = self\n .paths\n .iter()\n .map(move |p| {\n if p == Path::new(\"-\") {\n (p.to_path_buf(), None)\n } else {\n let mut wd = WalkDir::new(p);\n wd = wd.follow_links(follow_links || p.is_file());\n wd = wd.same_file_system(self.same_file_system);\n if let Some(max_depth) = max_depth {\n wd = wd.max_depth(max_depth);\n }\n if let Some(min_depth) = min_depth {\n wd = wd.min_depth(min_depth);\n }\n if let Some(ref sorter) = sorter {\n match sorter.clone() {\n Sorter::ByName(cmp) => {\n wd = wd.sort_by(move |a, b| {\n cmp(a.file_name(), b.file_name())\n });\n }\n Sorter::ByPath(cmp) => {\n wd = wd.sort_by(move |a, b| {\n cmp(a.path(), b.path())\n });\n }\n }\n }\n (p.to_path_buf(), Some(WalkEventIter::from(wd)))\n }\n })\n .collect::>()\n .into_iter();\n let ig_root = self.build_ignore();\n Walk {\n its,\n it: None,\n ig_root: ig_root.clone(),\n ig: ig_root.clone(),\n max_depth: self.max_depth,\n max_filesize: self.max_filesize,\n skip: self.skip.clone(),\n filter: self.filter.clone(),\n }\n }\n\n /// Build matchers for checking paths against ignore files without\n /// recursively walking the configured roots.\n ///\n /// The returned matchers use the path-based filtering configuration\n /// on this builder, including glob overrides, file type selections,\n /// parent ignore files, `.ignore`, `.gitignore`, global Git\n /// ignore files, explicitly added ignore files and custom ignore\n /// file names. For example, ripgrep configures `.rgignore` via\n /// [`WalkBuilder::add_custom_ignore_filename`]. Minimum and maximum depth\n /// limits, maximum file size and hidden-file filtering are also applied.\n /// Other options that only control traversal or require a directory entry,\n /// such as custom entry predicates, are not applied.\n ///\n /// One matcher is returned for each configured path, in the same order as\n /// the paths were added to this builder. Each matcher accepts paths\n /// relative to its own [`IncrementalIgnore::root`]. The matcher for the\n /// special `-` path representing standard input always returns a non-match\n /// for all inputs.\n ///\n /// Ignore matchers are loaded lazily and cached by directory.\n /// Thus, the first query may read ignore files from the root and\n /// its parents, while later queries reuse the compiled matchers.\n /// Errors encountered while loading ignore files are returned by\n /// [`IncrementalIgnore::matched_with_errors`]. Once an ignore file has\n /// been loaded, changes to it are not observed. Build new matchers to\n /// reload changed ignore files.\n ///\n /// Matchers built together share the builder's base ignore configuration\n /// and compiled parent matchers.\n pub fn build_matchers(&self) -> Vec {\n let ignore = self.build_ignore();\n let options = IncrementalIgnoreOptions {\n min_depth: self.min_depth,\n max_depth: self.max_depth,\n max_filesize: self.max_filesize,\n hidden: self.ig_builder.is_hidden(),\n follow_links: self.follow_links,\n };\n self.paths\n .iter()\n .map(move |path| {\n IncrementalIgnore::new(\n path.clone(),\n ignore.clone(),\n options.clone(),\n )\n })\n .collect()\n }\n\n /// Build a new `WalkParallel` iterator.\n ///\n /// Note that this *doesn't* return something that implements `Iterator`.\n /// Instead, the returned value must be run with a closure. e.g.,\n /// `builder.build_parallel().run(|| |path| { println!(\"{path:?}\"); WalkState::Continue })`.\n pub fn build_parallel(&self) -> WalkParallel {\n let ig_root = self.build_ignore();\n WalkParallel {\n paths: self.paths.clone().into_iter(),\n ig_root,\n max_depth: self.max_depth,\n min_depth: self.min_depth,\n max_filesize: self.max_filesize,\n follow_links: self.follow_links,\n same_file_system: self.same_file_system,\n threads: self.threads,\n skip: self.skip.clone(),\n filter: self.filter.clone(),\n }\n }\n\n /// Add a file path to the iterator.\n ///\n /// Each additional file path added is traversed recursively. This should\n /// be preferred over building multiple `Walk` iterators since this\n /// enables reusing resources across iteration.\n pub fn add>(&mut self, path: P) -> &mut WalkBuilder {\n self.paths.push(path.as_ref().to_path_buf());\n self\n }\n\n /// The maximum depth to recurse.\n ///\n /// The default, `None`, imposes no depth restriction.\n pub fn max_depth(&mut self, depth: Option) -> &mut WalkBuilder {\n self.max_depth = depth;\n if self.min_depth.is_some()\n && self.max_depth.is_some()\n && self.max_depth < self.min_depth\n {\n self.max_depth = self.min_depth;\n }\n self\n }\n\n /// The minimum depth to recurse.\n ///\n /// The default, `None`, imposes no minimum depth restriction.\n pub fn min_depth(&mut self, depth: Option) -> &mut WalkBuilder {\n self.min_depth = depth;\n if self.max_depth.is_some()\n && self.min_depth.is_some()\n && self.min_depth > self.max_depth\n {\n self.min_depth = self.max_depth;\n }\n self\n }\n\n /// Whether to follow symbolic links or not.\n pub fn follow_links(&mut self, yes: bool) -> &mut WalkBuilder {\n self.follow_links = yes;\n self\n }\n\n /// Whether to ignore files above the specified limit.\n pub fn max_filesize(&mut self, filesize: Option) -> &mut WalkBuilder {\n self.max_filesize = filesize;\n self\n }\n\n /// The number of threads to use for traversal.\n ///\n /// Note that this only has an effect when using `build_parallel`.\n ///\n /// The default setting is `0`, which chooses the number of threads\n /// automatically using heuristics.\n pub fn threads(&mut self, n: usize) -> &mut WalkBuilder {\n self.threads = n;\n self\n }\n\n /// Add a global ignore file to the matcher.\n ///\n /// This has lower precedence than all other sources of ignore rules.\n ///\n /// # Errors\n ///\n /// If there was a problem adding the ignore file, then an error is\n /// returned. Note that the error may indicate *partial* failure. For\n /// example, if an ignore file contains an invalid glob, all other globs\n /// are still applied.\n ///\n /// An error will also occur if this walker could not get the current\n /// working directory (and `WalkBuilder::current_dir` isn't set).\n pub fn add_ignore>(&mut self, path: P) -> Option {\n let path = path.as_ref();\n let Some(cwd) = self.get_or_set_current_dir() else {\n let err = std::io::Error::other(format!(\n \"CWD is not known, ignoring global gitignore {}\",\n path.display()\n ));\n return Some(err.into());\n };\n let mut builder = GitignoreBuilder::new(cwd);\n let mut errs = PartialErrorBuilder::default();\n errs.maybe_push(builder.add(path));\n match builder.build() {\n Ok(gi) => {\n self.ig_builder.add_ignore(gi);\n }\n Err(err) => {\n errs.push(err);\n }\n }\n errs.into_error_option()\n }\n\n /// Add a custom ignore file name\n ///\n /// These ignore files have higher precedence than all other ignore files.\n ///\n /// When specifying multiple names, earlier names have lower precedence than\n /// later names.\n pub fn add_custom_ignore_filename>(\n &mut self,\n file_name: S,\n ) -> &mut WalkBuilder {\n self.ig_builder.add_custom_ignore_filename(file_name);\n self\n }\n\n /// Add an override matcher.\n ///\n /// By default, no override matcher is used.\n ///\n /// This overrides any previous setting.\n pub fn overrides(&mut self, overrides: Override) -> &mut WalkBuilder {\n self.ig_builder.overrides(overrides);\n self\n }\n\n /// Add a file type matcher.\n ///\n /// By default, no file type matcher is used.\n ///\n /// This overrides any previous setting.\n pub fn types(&mut self, types: Types) -> &mut WalkBuilder {\n self.ig_builder.types(types);\n self\n }\n\n /// Enables all the standard ignore filters.\n ///\n /// This toggles, as a group, all the filters that are enabled by default:\n ///\n /// - [hidden()](#method.hidden)\n /// - [parents()](#method.parents)\n /// - [ignore()](#method.ignore)\n /// - [git_ignore()](#method.git_ignore)\n /// - [git_global()](#method.git_global)\n /// - [git_exclude()](#method.git_exclude)\n ///\n /// They may still be toggled individually after calling this function.\n ///\n /// This is (by definition) enabled by default.\n pub fn standard_filters(&mut self, yes: bool) -> &mut WalkBuilder {\n self.hidden(yes)\n .parents(yes)\n .ignore(yes)\n .git_ignore(yes)\n .git_global(yes)\n .git_exclude(yes)\n }\n\n /// Enables ignoring hidden files.\n ///\n /// This is enabled by default.\n pub fn hidden(&mut self, yes: bool) -> &mut WalkBuilder {\n self.ig_builder.hidden(yes);\n self\n }\n\n /// Enables reading ignore files from parent directories.\n ///\n /// If this is enabled, then .gitignore files in parent directories of each\n /// file path given are respected. Otherwise, they are ignored.\n ///\n /// This is enabled by default.\n pub fn parents(&mut self, yes: bool) -> &mut WalkBuilder {\n self.ig_builder.parents(yes);\n self\n }\n\n /// Enables reading `.ignore` files.\n ///\n /// `.ignore` files have the same semantics as `gitignore` files and are\n /// supported by search tools such as ripgrep and The Silver Searcher.\n ///\n /// This is enabled by default.\n pub fn ignore(&mut self, yes: bool) -> &mut WalkBuilder {\n self.ig_builder.ignore(yes);\n self\n }\n\n /// Enables reading a global gitignore file, whose path is specified in\n /// git's `core.excludesFile` config option.\n ///\n /// Git's config file location is `$HOME/.gitconfig`. If `$HOME/.gitconfig`\n /// does not exist or does not specify `core.excludesFile`, then\n /// `$XDG_CONFIG_HOME/git/ignore` is read. If `$XDG_CONFIG_HOME` is not\n /// set or is empty, then `$HOME/.config/git/ignore` is used instead.\n ///\n /// This is enabled by default.\n pub fn git_global(&mut self, yes: bool) -> &mut WalkBuilder {\n self.ig_builder.git_global(yes);\n self\n }\n\n /// Enables reading `.gitignore` files.\n ///\n /// `.gitignore` files have match semantics as described in the `gitignore`\n /// man page.\n ///\n /// This is enabled by default.\n pub fn git_ignore(&mut self, yes: bool) -> &mut WalkBuilder {\n self.ig_builder.git_ignore(yes);\n self\n }\n\n /// Enables reading `.git/info/exclude` files.\n ///\n /// `.git/info/exclude` files have match semantics as described in the\n /// `gitignore` man page.\n ///\n /// This is enabled by default.\n pub fn git_exclude(&mut self, yes: bool) -> &mut WalkBuilder {\n self.ig_builder.git_exclude(yes);\n self\n }\n\n /// Whether a git repository is required to apply git-related ignore\n /// rules (global rules, .gitignore and local exclude rules).\n ///\n /// When disabled, git-related ignore rules are applied even when searching\n /// outside a git repository.\n ///\n /// In particular, if this is `false` then `.gitignore` files will be read\n /// from parent directories above the git root directory containing `.git`,\n /// which is different from the git behavior.\n pub fn require_git(&mut self, yes: bool) -> &mut WalkBuilder {\n self.ig_builder.require_git(yes);\n self\n }\n\n /// Process ignore files case insensitively\n ///\n /// This is disabled by default.\n pub fn ignore_case_insensitive(&mut self, yes: bool) -> &mut WalkBuilder {\n self.ig_builder.ignore_case_insensitive(yes);\n self\n }\n\n /// Set a function for sorting directory entries by their path.\n ///\n /// If a compare function is set, the resulting iterator will return all\n /// paths in sorted order. The compare function will be called to compare\n /// entries from the same directory.\n ///\n /// This is like `sort_by_file_name`, except the comparator accepts\n /// a `&Path` instead of the base file name, which permits it to sort by\n /// more criteria.\n ///\n /// This method will override any previous sorter set by this method or\n /// by `sort_by_file_name`.\n ///\n /// Note that this is not used in the parallel iterator.\n pub fn sort_by_file_path(&mut self, cmp: F) -> &mut WalkBuilder\n where\n F: Fn(&Path, &Path) -> Ordering + Send + Sync + 'static,\n {\n self.sorter = Some(Sorter::ByPath(Arc::new(cmp)));\n self\n }\n\n /// Set a function for sorting directory entries by file name.\n ///\n /// If a compare function is set, the resulting iterator will return all\n /// paths in sorted order. The compare function will be called to compare\n /// names from entries from the same directory using only the name of the\n /// entry.\n ///\n /// This method will override any previous sorter set by this method or\n /// by `sort_by_file_path`.\n ///\n /// Note that this is not used in the parallel iterator.\n pub fn sort_by_file_name(&mut self, cmp: F) -> &mut WalkBuilder\n where\n F: Fn(&OsStr, &OsStr) -> Ordering + Send + Sync + 'static,\n {\n self.sorter = Some(Sorter::ByName(Arc::new(cmp)));\n self\n }\n\n /// Do not cross file system boundaries.\n ///\n /// When this option is enabled, directory traversal will not descend into\n /// directories that are on a different file system from the root path.\n ///\n /// Currently, this option is only supported on Unix and Windows. If this\n /// option is used on an unsupported platform, then directory traversal\n /// will immediately return an error and will not yield any entries.\n pub fn same_file_system(&mut self, yes: bool) -> &mut WalkBuilder {\n self.same_file_system = yes;\n self\n }\n\n /// Do not yield directory entries that are believed to correspond to\n /// stdout.\n ///\n /// This is useful when a command is invoked via shell redirection to a\n /// file that is also being read. For example, `grep -r foo ./ > results`\n /// might end up trying to search `results` even though it is also writing\n /// to it, which could cause an unbounded feedback loop. Setting this\n /// option prevents this from happening by skipping over the `results`\n /// file.\n ///\n /// This is disabled by default.\n pub fn skip_stdout(&mut self, yes: bool) -> &mut WalkBuilder {\n if yes {\n self.skip = stdout_handle().map(Arc::new);\n } else {\n self.skip = None;\n }\n self\n }\n\n /// Yields only entries which satisfy the given predicate and skips\n /// descending into directories that do not satisfy the given predicate.\n ///\n /// The predicate is applied to all entries. If the predicate is\n /// true, iteration carries on as normal. If the predicate is false, the\n /// entry is ignored and if it is a directory, it is not descended into.\n ///\n /// Note that the errors for reading entries that may not satisfy the\n /// predicate will still be yielded.\n ///\n /// Note also that only one filter predicate can be applied to a\n /// `WalkBuilder`. Calling this subsequent times overrides previous filter\n /// predicates.\n pub fn filter_entry

(&mut self, filter: P) -> &mut WalkBuilder\n where\n P: Fn(&DirEntry) -> bool + Send + Sync + 'static,\n {\n self.filter = Some(Filter(Arc::new(filter)));\n self\n }\n\n /// Set the current working directory used for matching global gitignores.\n ///\n /// If this is not set, then this walker will attempt to discover the\n /// correct path from the environment's current working directory. If\n /// that fails, then global gitignore files will be ignored.\n ///\n /// Global gitignore files come from things like a user's git configuration\n /// or from gitignore files added via [`WalkBuilder::add_ignore`].\n pub fn current_dir(\n &mut self,\n cwd: impl Into,\n ) -> &mut WalkBuilder {\n let cwd = cwd.into();\n self.ig_builder.current_dir(cwd.clone());\n if let Err(cwd) = self.global_gitignores_relative_to.set(Ok(cwd)) {\n // OK because `Err` from `set` implies a value exists.\n *self.global_gitignores_relative_to.get_mut().unwrap() = cwd;\n }\n self\n }\n\n /// Gets the currently configured CWD on this walk builder.\n ///\n /// This is \"lazy.\" That is, we only ask for the CWD from the environment\n /// if `WalkBuilder::current_dir` hasn't been called yet. And we ensure\n /// that we only do it once.\n fn get_or_set_current_dir(&self) -> Option<&Path> {\n let result = self.global_gitignores_relative_to.get_or_init(|| {\n let result = std::env::current_dir().map_err(Arc::new);\n match result {\n Ok(ref path) => {\n log::trace!(\n \"automatically discovered CWD: {}\",\n path.display()\n );\n }\n Err(ref err) => {\n log::debug!(\n \"failed to find CWD \\\n (global gitignores will be ignored): \\\n {err}\"\n );\n }\n }\n result\n });\n result.as_ref().ok().map(|path| &**path)\n }\n\n /// Build the root ignore matcher shared by all consumers of this builder.\n fn build_ignore(&self) -> Ignore {\n self.get_or_set_current_dir()\n .map(|cwd| self.ig_builder.build_with_cwd(Some(cwd.to_path_buf())))\n .unwrap_or_else(|| self.ig_builder.build())\n }\n}\n\n/// Walk is a recursive directory iterator over file paths in one or more\n/// directories.\n///\n/// Only file and directory paths matching the rules are returned. By default,\n/// ignore files like `.gitignore` are respected. The precise matching rules\n/// and precedence is explained in the documentation for `WalkBuilder`.\npub struct Walk {\n its: std::vec::IntoIter<(PathBuf, Option)>,\n it: Option,\n ig_root: Ignore,\n ig: Ignore,\n max_depth: Option,\n max_filesize: Option,\n skip: Option>,\n filter: Option,\n}\n\nimpl Walk {\n /// Creates a new recursive directory iterator for the file path given.\n ///\n /// Note that this uses default settings, which include respecting\n /// `.gitignore` files. To configure the iterator, use `WalkBuilder`\n /// instead.\n pub fn new>(path: P) -> Walk {\n WalkBuilder::new(path).build()\n }\n\n /// Create a new recursive directory iterator from the sequence of paths\n /// given.\n ///\n /// Note that if the provided iterator is empty, then `Walk` is guaranteed\n /// to yield zero entries.\n pub fn from_iter, I: IntoIterator>(\n paths: I,\n ) -> Walk {\n WalkBuilder::from_iter(paths).build()\n }\n\n fn skip_entry(&self, ent: &DirEntry) -> Result {\n if ent.depth() == 0 {\n return Ok(false);\n }\n // We ensure that trivial skipping is done before any other potentially\n // expensive operations (stat, filesystem other) are done. This seems\n // like an obvious optimization but becomes critical when filesystem\n // operations even as simple as stat can result in significant\n // overheads; an example of this was a bespoke filesystem layer in\n // Windows that hosted files remotely and would download them on-demand\n // when particular filesystem operations occurred. Users of this system\n // who ensured correct file-type filters were being used could still\n // get unnecessary file access resulting in large downloads.\n if should_skip_entry(&self.ig, ent) {\n return Ok(true);\n }\n if let Some(ref stdout) = self.skip {\n if path_equals(ent, stdout)? {\n return Ok(true);\n }\n }\n if self.max_filesize.is_some() && !ent.is_dir() {\n return Ok(skip_filesize(\n self.max_filesize.unwrap(),\n ent.path(),\n &ent.metadata().ok(),\n ));\n }\n if let Some(Filter(filter)) = &self.filter {\n if !filter(ent) {\n return Ok(true);\n }\n }\n Ok(false)\n }\n}\n\nimpl Iterator for Walk {\n type Item = Result;\n\n #[inline(always)]\n fn next(&mut self) -> Option> {\n loop {\n let ev = match self.it.as_mut().and_then(|it| it.next()) {\n Some(ev) => ev,\n None => {\n match self.its.next() {\n None => return None,\n Some((_, None)) => {\n return Some(Ok(DirEntry::new_stdin()));\n }\n Some((path, Some(it))) => {\n self.it = Some(it);\n if path.is_dir() {\n let (ig, err) = self.ig_root.add_parents(path);\n self.ig = ig;\n if let Some(err) = err {\n return Some(Err(err));\n }\n } else {\n self.ig = self.ig_root.clone();\n }\n }\n }\n continue;\n }\n };\n match ev {\n Err(err) => {\n return Some(Err(Error::from_walkdir(err)));\n }\n Ok(WalkEvent::Exit) => {\n self.ig = self.ig.parent().unwrap();\n }\n Ok(WalkEvent::Dir(ent)) => {\n let mut ent = DirEntry::new_walkdir(ent, None);\n let should_skip = match self.skip_entry(&ent) {\n Err(err) => return Some(Err(err)),\n Ok(should_skip) => should_skip,\n };\n if should_skip {\n self.it.as_mut().unwrap().it.skip_current_dir();\n // Still need to push this on the stack because\n // we'll get a WalkEvent::Exit event for this dir.\n // Its ignore files cannot apply to any visited entry.\n let (igtmp, _) =\n self.ig.add_child_with_entries(ent.path(), &[]);\n self.ig = igtmp;\n continue;\n }\n let (igtmp, err) = if self.max_depth == Some(ent.depth()) {\n self.ig.add_child_with_entries(ent.path(), &[])\n } else {\n self.ig.add_child(ent.path())\n };\n self.ig = igtmp;\n ent.err = err;\n return Some(Ok(ent));\n }\n Ok(WalkEvent::File(ent)) => {\n let ent = DirEntry::new_walkdir(ent, None);\n let should_skip = match self.skip_entry(&ent) {\n Err(err) => return Some(Err(err)),\n Ok(should_skip) => should_skip,\n };\n if should_skip {\n continue;\n }\n return Some(Ok(ent));\n }\n }\n }\n }\n}\n\nimpl std::iter::FusedIterator for Walk {}\n\n/// WalkEventIter transforms a WalkDir iterator into an iterator that more\n/// accurately describes the directory tree. Namely, it emits events that are\n/// one of three types: directory, file or \"exit.\" An \"exit\" event means that\n/// the entire contents of a directory have been enumerated.\nstruct WalkEventIter {\n depth: usize,\n it: walkdir::IntoIter,\n next: Option>,\n}\n\n#[derive(Debug)]\nenum WalkEvent {\n Dir(walkdir::DirEntry),\n File(walkdir::DirEntry),\n Exit,\n}\n\nimpl From for WalkEventIter {\n fn from(it: WalkDir) -> WalkEventIter {\n WalkEventIter { depth: 0, it: it.into_iter(), next: None }\n }\n}\n\nimpl Iterator for WalkEventIter {\n type Item = walkdir::Result;\n\n #[inline(always)]\n fn next(&mut self) -> Option> {\n let dent = self.next.take().or_else(|| self.it.next());\n let depth = match dent {\n None => 0,\n Some(Ok(ref dent)) => dent.depth(),\n Some(Err(ref err)) => err.depth(),\n };\n if depth < self.depth {\n self.depth -= 1;\n self.next = dent;\n return Some(Ok(WalkEvent::Exit));\n }\n self.depth = depth;\n match dent {\n None => None,\n Some(Err(err)) => Some(Err(err)),\n Some(Ok(dent)) => {\n if walkdir_is_dir(&dent) {\n self.depth += 1;\n Some(Ok(WalkEvent::Dir(dent)))\n } else {\n Some(Ok(WalkEvent::File(dent)))\n }\n }\n }\n }\n}\n\n/// WalkState is used in the parallel recursive directory iterator to indicate\n/// whether walking should continue as normal, skip descending into a\n/// particular directory or quit the walk entirely.\n#[derive(Clone, Copy, Debug, Eq, PartialEq)]\npub enum WalkState {\n /// Continue walking as normal.\n Continue,\n /// If the directory entry given is a directory, don't descend into it.\n /// In all other cases, this has no effect.\n Skip,\n /// Quit the entire iterator as soon as possible.\n ///\n /// Note that this is an inherently asynchronous action. It is possible\n /// for more entries to be yielded even after instructing the iterator\n /// to quit.\n Quit,\n}\n\nimpl WalkState {\n fn is_continue(&self) -> bool {\n *self == WalkState::Continue\n }\n\n fn is_quit(&self) -> bool {\n *self == WalkState::Quit\n }\n}\n\n/// A builder for constructing a visitor when using [`WalkParallel::visit`].\n/// The builder will be called for each thread started by `WalkParallel`. The\n/// visitor returned from each builder is then called for every directory\n/// entry.\npub trait ParallelVisitorBuilder<'s> {\n /// Create per-thread `ParallelVisitor`s for `WalkParallel`.\n fn build(&mut self) -> Box;\n}\n\nimpl<'a, 's, P: ParallelVisitorBuilder<'s>> ParallelVisitorBuilder<'s>\n for &'a mut P\n{\n fn build(&mut self) -> Box {\n (**self).build()\n }\n}\n\n/// Receives files and directories for the current thread.\n///\n/// Setup for the traversal can be implemented as part of\n/// [`ParallelVisitorBuilder::build`]. Teardown when traversal finishes can be\n/// implemented by implementing the `Drop` trait on your traversal type.\npub trait ParallelVisitor: Send {\n /// Receives files and directories for the current thread. This is called\n /// once for every directory entry visited by traversal.\n fn visit(&mut self, entry: Result) -> WalkState;\n}\n\nstruct FnBuilder {\n builder: F,\n}\n\nimpl<'s, F: FnMut() -> FnVisitor<'s>> ParallelVisitorBuilder<'s>\n for FnBuilder\n{\n fn build(&mut self) -> Box {\n let visitor = (self.builder)();\n Box::new(FnVisitorImp { visitor })\n }\n}\n\ntype FnVisitor<'s> =\n Box) -> WalkState + Send + 's>;\n\nstruct FnVisitorImp<'s> {\n visitor: FnVisitor<'s>,\n}\n\nimpl<'s> ParallelVisitor for FnVisitorImp<'s> {\n fn visit(&mut self, entry: Result) -> WalkState {\n (self.visitor)(entry)\n }\n}\n\n/// WalkParallel is a parallel recursive directory iterator over files paths\n/// in one or more directories.\n///\n/// Only file and directory paths matching the rules are returned. By default,\n/// ignore files like `.gitignore` are respected. The precise matching rules\n/// and precedence is explained in the documentation for `WalkBuilder`.\n///\n/// Unlike `Walk`, this uses multiple threads for traversing a directory.\npub struct WalkParallel {\n paths: std::vec::IntoIter,\n ig_root: Ignore,\n max_filesize: Option,\n max_depth: Option,\n min_depth: Option,\n follow_links: bool,\n same_file_system: bool,\n threads: usize,\n skip: Option>,\n filter: Option,\n}\n\nimpl WalkParallel {\n /// Execute the parallel recursive directory iterator. `mkf` is called\n /// for each thread used for iteration. The function produced by `mkf`\n /// is then in turn called for each visited file path.\n pub fn run<'s, F>(self, mkf: F)\n where\n F: FnMut() -> FnVisitor<'s>,\n {\n self.visit(&mut FnBuilder { builder: mkf })\n }\n\n /// Execute the parallel recursive directory iterator using a custom\n /// visitor.\n ///\n /// The builder given is used to construct a visitor for every thread\n /// used by this traversal. The visitor returned from each builder is then\n /// called for every directory entry seen by that thread.\n ///\n /// Typically, creating a custom visitor is useful if you need to perform\n /// some kind of cleanup once traversal is finished. This can be achieved\n /// by implementing `Drop` for your builder (or for your visitor, if you\n /// want to execute cleanup for every thread that is launched).\n ///\n /// For example, each visitor might build up a data structure of results\n /// corresponding to the directory entries seen for each thread. Since each\n /// visitor runs on only one thread, this build-up can be done without\n /// synchronization. Then, once traversal is complete, all of the results\n /// can be merged together into a single data structure.\n pub fn visit(mut self, builder: &mut dyn ParallelVisitorBuilder<'_>) {\n let threads = self.threads();\n let mut stack = vec![];\n {\n let mut visitor = builder.build();\n let mut paths = Vec::new().into_iter();\n std::mem::swap(&mut paths, &mut self.paths);\n // Send the initial set of root paths to the pool of workers. Note\n // that we only send directories. For files, we send to them the\n // callback directly.\n for path in paths {\n let (dent, root_device) = if path == Path::new(\"-\") {\n (DirEntry::new_stdin(), None)\n } else {\n let root_device = if !self.same_file_system {\n None\n } else {\n match device_num(&path) {\n Ok(root_device) => Some(root_device),\n Err(err) => {\n let err = Error::Io(err).with_path(path);\n if visitor.visit(Err(err)).is_quit() {\n return;\n }\n continue;\n }\n }\n };\n match DirEntryRaw::from_path(0, path, false) {\n Ok(dent) => {\n (DirEntry::new_raw(dent, None), root_device)\n }\n Err(err) => {\n if visitor.visit(Err(err)).is_quit() {\n return;\n }\n continue;\n }\n }\n };\n stack.push(Message::Work(Work {\n dent,\n ignore: self.ig_root.clone(),\n root_device,\n }));\n }\n // ... but there's no need to start workers if we don't need them.\n if stack.is_empty() {\n return;\n }\n }\n // Create the workers and then wait for them to finish.\n let quit_now = Arc::new(AtomicBool::new(false));\n let active_workers = Arc::new(AtomicUsize::new(threads));\n let stacks = Stack::new_for_each_thread(threads, stack);\n // Collect all of the workers first. In the case that\n // `builder.build()` panics, we want that to happen and\n // propagate before we actually start to run any of the\n // workers.\n let workers: Vec<_> = stacks\n .into_iter()\n .map(|stack| Worker {\n visitor: builder.build(),\n stack,\n quit_now: quit_now.clone(),\n active_workers: active_workers.clone(),\n max_depth: self.max_depth,\n min_depth: self.min_depth,\n max_filesize: self.max_filesize,\n follow_links: self.follow_links,\n skip: self.skip.clone(),\n filter: self.filter.clone(),\n })\n .collect();\n std::thread::scope(|s| {\n let handles: Vec<_> = workers\n .into_iter()\n .map(|worker| s.spawn(|| worker.run()))\n .collect();\n for handle in handles {\n handle.join().unwrap();\n }\n });\n }\n\n fn threads(&self) -> usize {\n if self.threads == 0 {\n std::thread::available_parallelism().map_or(1, |n| n.get()).min(12)\n } else {\n self.threads\n }\n }\n}\n\n/// Message is the set of instructions that a worker knows how to process.\nenum Message {\n /// A work item corresponds to a directory that should be descended into.\n /// Work items for entries that should be skipped or ignored should not\n /// be produced.\n Work(Work),\n /// This instruction indicates that the worker should quit.\n Quit,\n}\n\n/// A unit of work for each worker to process.\n///\n/// Each unit of work corresponds to a directory that should be descended\n/// into.\nstruct Work {\n /// The directory entry.\n dent: DirEntry,\n /// Any ignore matchers that have been built for this directory's parents.\n ignore: Ignore,\n /// The root device number. When present, only files with the same device\n /// number should be considered.\n root_device: Option,\n}\n\n#[derive(Default)]\nstruct ReadDirResult {\n entries: Vec,\n errors: Vec,\n}\n\nimpl Work {\n /// Returns true if and only if this work item is a directory.\n fn is_dir(&self) -> bool {\n self.dent.is_dir()\n }\n\n /// Returns true if and only if this work item is a symlink.\n fn is_symlink(&self) -> bool {\n self.dent.file_type().map_or(false, |ft| ft.is_symlink())\n }\n\n /// Adds ignore rules for parent directories.\n ///\n /// Note that this only applies to entries at depth 0. On all other\n /// entries, this is a no-op.\n fn add_parents(&mut self) -> Option {\n if self.dent.depth() > 0 {\n return None;\n }\n // At depth 0, the path of this entry is a root path, so we can\n // use it directly to add parent ignore rules.\n let (ig, err) = self.ignore.add_parents(self.dent.path());\n self.ignore = ig;\n err\n }\n\n /// Adds ignore rules for this directory without reading its contents.\n fn add_ignore(&mut self) {\n let (ig, err) = self.ignore.add_child(self.dent.path());\n self.ignore = ig;\n self.dent.err = err;\n }\n\n /// Reads the directory contents of this work item and adds ignore\n /// rules for this directory.\n ///\n /// If there was a problem with reading the directory contents, then\n /// an error is returned. If there was a problem reading the ignore\n /// rules for this directory, then the error is attached to this\n /// work item's directory entry.\n fn read_dir(&mut self) -> Result {\n let readdir = match fs::read_dir(self.dent.path()) {\n Ok(readdir) => readdir,\n Err(err) => {\n let err = Error::from(err)\n .with_path(self.dent.path())\n .with_depth(self.dent.depth());\n return Err(err);\n }\n };\n // Actually descend into the directory and read its contents\n let mut result = ReadDirResult::default();\n for entry in readdir {\n match entry {\n Ok(entry) => result.entries.push(entry),\n Err(err) => result.errors.push(\n Error::from(err)\n .with_path(self.dent.path())\n .with_depth(self.dent.depth() + 1),\n ),\n }\n }\n let (ig, err) = self\n .ignore\n .add_child_with_entries(self.dent.path(), &result.entries);\n self.ignore = ig;\n self.dent.err = err;\n Ok(result)\n }\n}\n\n/// A work-stealing stack.\n#[derive(Debug)]\nstruct Stack {\n /// This thread's index.\n index: usize,\n /// The thread-local stack.\n deque: Deque,\n /// The work stealers.\n stealers: Arc<[Stealer]>,\n}\n\nimpl Stack {\n /// Create a work-stealing stack for each thread. The given messages\n /// correspond to the initial paths to start the search at. They will\n /// be distributed automatically to each stack in a round-robin fashion.\n fn new_for_each_thread(threads: usize, init: Vec) -> Vec {\n // Using new_lifo() ensures each worker operates depth-first, not\n // breadth-first. We do depth-first because a breadth first traversal\n // on wide directories with a lot of gitignores is disastrous (for\n // example, searching a directory tree containing all of crates.io).\n let deques: Vec> =\n std::iter::repeat_with(Deque::new_lifo).take(threads).collect();\n let stealers = Arc::<[Stealer]>::from(\n deques.iter().map(Deque::stealer).collect::>(),\n );\n let stacks: Vec = deques\n .into_iter()\n .enumerate()\n .map(|(index, deque)| Stack {\n index,\n deque,\n stealers: stealers.clone(),\n })\n .collect();\n // Distribute the initial messages, reverse the order to cancel out\n // the other reversal caused by the inherent LIFO processing of the\n // per-thread stacks which are filled here.\n init.into_iter()\n .rev()\n .zip(stacks.iter().cycle())\n .for_each(|(m, s)| s.push(m));\n stacks\n }\n\n /// Push a message.\n fn push(&self, msg: Message) {\n self.deque.push(msg);\n }\n\n /// Pop a message.\n fn pop(&self) -> Option {\n self.deque.pop().or_else(|| self.steal())\n }\n\n /// Steal a message from another queue.\n fn steal(&self) -> Option {\n // For fairness, try to steal from index + 1, index + 2, ... len - 1,\n // then wrap around to 0, 1, ... index - 1.\n let (left, right) = self.stealers.split_at(self.index);\n // Don't steal from ourselves\n let right = &right[1..];\n\n right\n .iter()\n .chain(left.iter())\n .map(|s| s.steal_batch_and_pop(&self.deque))\n .find_map(|s| s.success())\n }\n}\n\n/// A worker is responsible for descending into directories, updating the\n/// ignore matchers, producing new work and invoking the caller's callback.\n///\n/// Note that a worker is *both* a producer and a consumer.\nstruct Worker<'s> {\n /// The caller's callback.\n visitor: Box,\n /// A work-stealing stack of work to do.\n ///\n /// We use a stack instead of a channel because a stack lets us visit\n /// directories in depth first order. This can substantially reduce peak\n /// memory usage by keeping both the number of file paths and gitignore\n /// matchers in memory lower.\n stack: Stack,\n /// Whether all workers should terminate at the next opportunity. Note\n /// that we need this because we don't want other `Work` to be done after\n /// we quit. We wouldn't need this if have a priority channel.\n quit_now: Arc,\n /// The number of currently active workers.\n active_workers: Arc,\n /// The maximum depth of directories to descend. A value of `0` means no\n /// descension at all.\n max_depth: Option,\n /// The minimum depth of directories to descend.\n min_depth: Option,\n /// The maximum size a searched file can be (in bytes). If a file exceeds\n /// this size it will be skipped.\n max_filesize: Option,\n /// Whether to follow symbolic links or not. When this is enabled, loop\n /// detection is performed.\n follow_links: bool,\n /// A file handle to skip, currently is either `None` or stdout, if it's\n /// a file and it has been requested to skip files identical to stdout.\n skip: Option>,\n /// A predicate applied to dir entries. If true, the entry and all\n /// children will be skipped.\n filter: Option,\n}\n\nimpl<'s> Worker<'s> {\n /// Runs this worker until there is no more work left to do.\n ///\n /// The worker will call the caller's callback for all entries that aren't\n /// skipped by the ignore matcher.\n fn run(mut self) {\n while let Some(work) = self.get_work() {\n if let WalkState::Quit = self.run_one(work) {\n self.quit_now();\n }\n }\n }\n\n fn run_one(&mut self, mut work: Work) -> WalkState {\n let should_visit = self\n .min_depth\n .map(|min_depth| work.dent.depth() >= min_depth)\n .unwrap_or(true);\n\n // If the work is not a directory, then we can just execute the\n // caller's callback immediately and move on.\n if work.is_symlink() || !work.is_dir() {\n return if should_visit {\n self.visitor.visit(Ok(work.dent))\n } else {\n WalkState::Continue\n };\n }\n if let Some(err) = work.add_parents() {\n let state = self.visitor.visit(Err(err));\n if state.is_quit() {\n return state;\n }\n }\n\n let descend = if let Some(root_device) = work.root_device {\n match is_same_file_system(root_device, work.dent.path()) {\n Ok(true) => true,\n Ok(false) => false,\n Err(err) => {\n let state = self.visitor.visit(Err(err));\n if state.is_quit() {\n return state;\n }\n false\n }\n }\n } else {\n true\n };\n\n // Try to read the directory first before we transfer ownership\n // to the provided closure. Do not unwrap it immediately, though,\n // as we may receive an `Err` value e.g. in the case when we do not\n // have sufficient read permissions to list the directory.\n // In that case we still want to provide the closure with a valid\n // entry before passing the error value.\n let depth = work.dent.depth();\n let readdir = if descend && self.max_depth.is_none_or(|m| depth < m) {\n Some(work.read_dir())\n } else {\n work.add_ignore();\n None\n };\n if should_visit {\n let state = self.visitor.visit(Ok(work.dent));\n if !state.is_continue() {\n return state;\n }\n }\n if !descend {\n return WalkState::Skip;\n }\n\n let readdir = match readdir {\n Some(readdir) => readdir,\n None => return WalkState::Skip,\n };\n let readdir = match readdir {\n Ok(readdir) => readdir,\n Err(err) => {\n return self.visitor.visit(Err(err));\n }\n };\n\n for result in readdir.entries {\n let state = self.generate_work(\n &work.ignore,\n depth + 1,\n work.root_device,\n result,\n );\n if state.is_quit() {\n return state;\n }\n }\n for err in readdir.errors {\n let state = self.visitor.visit(Err(err));\n if state.is_quit() {\n return state;\n }\n }\n WalkState::Continue\n }\n\n /// Decides whether to submit the given directory entry as a file to\n /// search.\n ///\n /// If the entry is a path that should be ignored, then this is a no-op.\n /// Otherwise, the entry is pushed on to the queue. (The actual execution\n /// of the callback happens in `run_one`.)\n ///\n /// If an error occurs while reading the entry, then it is sent to the\n /// caller's callback.\n ///\n /// `ig` is the `Ignore` matcher for the parent directory. `depth` should\n /// be the depth of this entry. `result` should be the item yielded by\n /// a directory iterator.\n fn generate_work(\n &mut self,\n ig: &Ignore,\n depth: usize,\n root_device: Option,\n fs_dent: fs::DirEntry,\n ) -> WalkState {\n let mut dent = match DirEntryRaw::from_entry(depth, &fs_dent) {\n Ok(dent) => DirEntry::new_raw(dent, None),\n Err(err) => {\n return self.visitor.visit(Err(err));\n }\n };\n let is_symlink = dent.file_type().map_or(false, |ft| ft.is_symlink());\n if self.follow_links && is_symlink {\n let path = dent.path().to_path_buf();\n dent = match DirEntryRaw::from_path(depth, path, true) {\n Ok(dent) => DirEntry::new_raw(dent, None),\n Err(err) => {\n return self.visitor.visit(Err(err));\n }\n };\n if dent.is_dir() {\n if let Err(err) = check_symlink_loop(ig, dent.path(), depth) {\n return self.visitor.visit(Err(err));\n }\n }\n }\n // N.B. See analogous call in the single-threaded implementation about\n // why it's important for this to come before the checks below.\n if should_skip_entry(ig, &dent) {\n return WalkState::Continue;\n }\n if let Some(ref stdout) = self.skip {\n let is_stdout = match path_equals(&dent, stdout) {\n Ok(is_stdout) => is_stdout,\n Err(err) => return self.visitor.visit(Err(err)),\n };\n if is_stdout {\n return WalkState::Continue;\n }\n }\n let should_skip_filesize =\n if self.max_filesize.is_some() && !dent.is_dir() {\n skip_filesize(\n self.max_filesize.unwrap(),\n dent.path(),\n &dent.metadata().ok(),\n )\n } else {\n false\n };\n let should_skip_filtered =\n if let Some(Filter(predicate)) = &self.filter {\n !predicate(&dent)\n } else {\n false\n };\n if !should_skip_filesize && !should_skip_filtered {\n self.send(Work { dent, ignore: ig.clone(), root_device });\n }\n WalkState::Continue\n }\n\n /// Returns the next directory to descend into.\n ///\n /// If all work has been exhausted, then this returns None. The worker\n /// should then subsequently quit.\n fn get_work(&mut self) -> Option {\n let mut value = self.recv();\n loop {\n // Simulate a priority channel: If quit_now flag is set, we can\n // receive only quit messages.\n if self.is_quit_now() {\n value = Some(Message::Quit)\n }\n match value {\n Some(Message::Work(work)) => {\n return Some(work);\n }\n Some(Message::Quit) => {\n // Repeat quit message to wake up sleeping threads, if\n // any. The domino effect will ensure that every thread\n // will quit.\n self.send_quit();\n return None;\n }\n None => {\n if self.deactivate_worker() == 0 {\n // If deactivate_worker() returns 0, every worker thread\n // is currently within the critical section between the\n // acquire in deactivate_worker() and the release in\n // activate_worker() below. For this to happen, every\n // worker's local deque must be simultaneously empty,\n // meaning there is no more work left at all.\n self.send_quit();\n return None;\n }\n // Wait for next `Work` or `Quit` message.\n loop {\n if self.is_quit_now() {\n return None;\n }\n if let Some(v) = self.recv() {\n self.activate_worker();\n value = Some(v);\n break;\n }\n // Our stack isn't blocking. Instead of burning the\n // CPU waiting, we let the thread sleep for a bit. In\n // general, this tends to only occur once the search is\n // approaching termination.\n let dur = std::time::Duration::from_millis(1);\n std::thread::sleep(dur);\n }\n }\n }\n }\n }\n\n /// Indicates that all workers should quit immediately.\n fn quit_now(&self) {\n self.quit_now.store(true, AtomicOrdering::SeqCst);\n }\n\n /// Returns true if this worker should quit immediately.\n fn is_quit_now(&self) -> bool {\n self.quit_now.load(AtomicOrdering::SeqCst)\n }\n\n /// Send work.\n fn send(&self, work: Work) {\n self.stack.push(Message::Work(work));\n }\n\n /// Send a quit message.\n fn send_quit(&self) {\n self.stack.push(Message::Quit);\n }\n\n /// Receive work.\n fn recv(&self) -> Option {\n self.stack.pop()\n }\n\n /// Deactivates a worker and returns the number of currently active workers.\n fn deactivate_worker(&self) -> usize {\n self.active_workers.fetch_sub(1, AtomicOrdering::Acquire) - 1\n }\n\n /// Reactivates a worker.\n fn activate_worker(&self) {\n self.active_workers.fetch_add(1, AtomicOrdering::Release);\n }\n}\n\nimpl<'s> Drop for Worker<'s> {\n fn drop(&mut self) {\n if std::thread::panicking() {\n self.quit_now();\n }\n }\n}\n\nfn check_symlink_loop(\n ig_parent: &Ignore,\n child_path: &Path,\n child_depth: usize,\n) -> Result<(), Error> {\n let hchild = Handle::from_path(child_path).map_err(|err| {\n Error::from(err).with_path(child_path).with_depth(child_depth)\n })?;\n for ig in ig_parent.parents().take_while(|ig| !ig.is_absolute_parent()) {\n let h = Handle::from_path(ig.path()).map_err(|err| {\n Error::from(err).with_path(child_path).with_depth(child_depth)\n })?;\n if hchild == h {\n return Err(Error::Loop {\n ancestor: ig.path().to_path_buf(),\n child: child_path.to_path_buf(),\n }\n .with_depth(child_depth));\n }\n }\n Ok(())\n}\n\n// Before calling this function, make sure that you ensure that is really\n// necessary as the arguments imply a file stat.\nfn skip_filesize(\n max_filesize: u64,\n path: &Path,\n ent: &Option,\n) -> bool {\n let filesize = match *ent {\n Some(ref md) => Some(md.len()),\n None => None,\n };\n\n if let Some(fs) = filesize {\n if fs > max_filesize {\n log::debug!(\"ignoring {}: {} bytes\", path.display(), fs);\n true\n } else {\n false\n }\n } else {\n false\n }\n}\n\nfn should_skip_entry(ig: &Ignore, dent: &DirEntry) -> bool {\n let m = ig.matched_dir_entry(dent);\n if m.is_ignore() {\n log::debug!(\"ignoring {}: {:?}\", dent.path().display(), m);\n true\n } else if m.is_whitelist() {\n log::debug!(\"whitelisting {}: {:?}\", dent.path().display(), m);\n false\n } else {\n false\n }\n}\n\n/// Returns a handle to stdout for filtering search.\n///\n/// A handle is returned if and only if stdout is being redirected to a file.\n/// The handle returned corresponds to that file.\n///\n/// This can be used to ensure that we do not attempt to search a file that we\n/// may also be writing to.\nfn stdout_handle() -> Option {\n let h = match Handle::stdout() {\n Err(_) => return None,\n Ok(h) => h,\n };\n let md = match h.as_file().metadata() {\n Err(_) => return None,\n Ok(md) => md,\n };\n if !md.is_file() {\n return None;\n }\n Some(h)\n}\n\n/// Returns true if and only if the given directory entry is believed to be\n/// equivalent to the given handle. If there was a problem querying the path\n/// for information to determine equality, then that error is returned.\nfn path_equals(dent: &DirEntry, handle: &Handle) -> Result {\n #[cfg(unix)]\n fn never_equal(dent: &DirEntry, handle: &Handle) -> bool {\n dent.ino() != Some(handle.ino())\n }\n\n #[cfg(not(unix))]\n fn never_equal(_: &DirEntry, _: &Handle) -> bool {\n false\n }\n\n // If we know for sure that these two things aren't equal, then avoid\n // the costly extra stat call to determine equality.\n if dent.is_stdin() || never_equal(dent, handle) {\n return Ok(false);\n }\n Handle::from_path(dent.path()).map(|h| &h == handle).map_err(|err| {\n Error::Io(err).with_depth(dent.depth()).with_path(dent.path())\n })\n}\n\n/// Returns true if the given walkdir entry corresponds to a directory.\n///\n/// This is normally just `dent.file_type().is_dir()`, but when we aren't\n/// following symlinks, the root directory entry may be a symlink to a\n/// directory that we *do* follow---by virtue of it being specified by the user\n/// explicitly. In that case, we need to follow the symlink and query whether\n/// it's a directory or not. But we only do this for root entries to avoid an\n/// additional stat check in most cases.\nfn walkdir_is_dir(dent: &walkdir::DirEntry) -> bool {\n if dent.file_type().is_dir() {\n return true;\n }\n if !dent.file_type().is_symlink() || dent.depth() > 0 {\n return false;\n }\n dent.path().metadata().ok().map_or(false, |md| md.file_type().is_dir())\n}\n\n/// Returns true if and only if the given path is on the same device as the\n/// given root device.\nfn is_same_file_system(root_device: u64, path: &Path) -> Result {\n let dent_device =\n device_num(path).map_err(|err| Error::Io(err).with_path(path))?;\n Ok(root_device == dent_device)\n}\n\n#[cfg(unix)]\nfn device_num>(path: P) -> io::Result {\n use std::os::unix::fs::MetadataExt;\n\n path.as_ref().metadata().map(|md| md.dev())\n}\n\n#[cfg(windows)]\nfn device_num>(path: P) -> io::Result {\n use winapi_util::{Handle, file};\n\n let h = Handle::from_path_any(path)?;\n file::information(h).map(|info| info.volume_serial_number())\n}\n\n#[cfg(not(any(unix, windows)))]\nfn device_num>(_: P) -> io::Result {\n Err(io::Error::new(\n io::ErrorKind::Other,\n \"walkdir: same_file_system option not supported on this platform\",\n ))\n}\n\n#[cfg(test)]\nmod tests {\n use std::ffi::OsStr;\n use std::fs::{self, File};\n use std::io::Write;\n use std::path::Path;\n use std::sync::{Arc, Mutex};\n\n use super::{DirEntry, WalkBuilder, WalkState};\n use crate::tests::TempDir;\n\n fn wfile>(path: P, contents: &str) {\n let mut file = File::create(path).unwrap();\n file.write_all(contents.as_bytes()).unwrap();\n }\n\n fn wfile_size>(path: P, size: u64) {\n let file = File::create(path).unwrap();\n file.set_len(size).unwrap();\n }\n\n #[cfg(unix)]\n fn symlink, Q: AsRef>(src: P, dst: Q) {\n use std::os::unix::fs::symlink;\n symlink(src, dst).unwrap();\n }\n\n fn mkdirp>(path: P) {\n fs::create_dir_all(path).unwrap();\n }\n\n fn normal_path(unix: &str) -> String {\n if cfg!(windows) { unix.replace(\"\\\\\", \"/\") } else { unix.to_string() }\n }\n\n fn walk_collect(prefix: &Path, builder: &WalkBuilder) -> Vec {\n let mut paths = vec![];\n for result in builder.build() {\n let dent = match result {\n Err(_) => continue,\n Ok(dent) => dent,\n };\n let path = dent.path().strip_prefix(prefix).unwrap();\n if path.as_os_str().is_empty() {\n continue;\n }\n paths.push(normal_path(path.to_str().unwrap()));\n }\n paths.sort();\n paths\n }\n\n fn walk_collect_parallel(\n prefix: &Path,\n builder: &WalkBuilder,\n ) -> Vec {\n let mut paths = vec![];\n for dent in walk_collect_entries_parallel(builder) {\n let path = dent.path().strip_prefix(prefix).unwrap();\n if path.as_os_str().is_empty() {\n continue;\n }\n paths.push(normal_path(path.to_str().unwrap()));\n }\n paths.sort();\n paths\n }\n\n fn walk_collect_entries_parallel(builder: &WalkBuilder) -> Vec {\n let dents = Arc::new(Mutex::new(vec![]));\n builder.build_parallel().run(|| {\n let dents = dents.clone();\n Box::new(move |result| {\n if let Ok(dent) = result {\n dents.lock().unwrap().push(dent);\n }\n WalkState::Continue\n })\n });\n\n let dents = dents.lock().unwrap();\n dents.to_vec()\n }\n\n fn mkpaths(paths: &[&str]) -> Vec {\n let mut paths: Vec<_> = paths.iter().map(|s| s.to_string()).collect();\n paths.sort();\n paths\n }\n\n fn tmpdir() -> TempDir {\n TempDir::new().unwrap()\n }\n\n fn assert_paths(prefix: &Path, builder: &WalkBuilder, expected: &[&str]) {\n let got = walk_collect(prefix, builder);\n assert_eq!(got, mkpaths(expected), \"single threaded\");\n let got = walk_collect_parallel(prefix, builder);\n assert_eq!(got, mkpaths(expected), \"parallel\");\n }\n\n #[test]\n fn no_ignores() {\n let td = tmpdir();\n mkdirp(td.path().join(\"a/b/c\"));\n mkdirp(td.path().join(\"x/y\"));\n wfile(td.path().join(\"a/b/foo\"), \"\");\n wfile(td.path().join(\"x/y/foo\"), \"\");\n\n assert_paths(\n td.path(),\n &WalkBuilder::new(td.path()),\n &[\"x\", \"x/y\", \"x/y/foo\", \"a\", \"a/b\", \"a/b/foo\", \"a/b/c\"],\n );\n }\n\n #[test]\n fn custom_ignore() {\n let td = tmpdir();\n let custom_ignore = \".customignore\";\n mkdirp(td.path().join(\"a\"));\n wfile(td.path().join(custom_ignore), \"foo\");\n wfile(td.path().join(\"foo\"), \"\");\n wfile(td.path().join(\"a/foo\"), \"\");\n wfile(td.path().join(\"bar\"), \"\");\n wfile(td.path().join(\"a/bar\"), \"\");\n\n let mut builder = WalkBuilder::new(td.path());\n builder.add_custom_ignore_filename(&custom_ignore);\n assert_paths(td.path(), &builder, &[\"bar\", \"a\", \"a/bar\"]);\n }\n\n #[test]\n fn custom_ignore_exclusive_use() {\n let td = tmpdir();\n let custom_ignore = \".customignore\";\n mkdirp(td.path().join(\"a\"));\n wfile(td.path().join(custom_ignore), \"foo\");\n wfile(td.path().join(\"foo\"), \"\");\n wfile(td.path().join(\"a/foo\"), \"\");\n wfile(td.path().join(\"bar\"), \"\");\n wfile(td.path().join(\"a/bar\"), \"\");\n\n let mut builder = WalkBuilder::new(td.path());\n builder.ignore(false);\n builder.git_ignore(false);\n builder.git_global(false);\n builder.git_exclude(false);\n builder.add_custom_ignore_filename(&custom_ignore);\n assert_paths(td.path(), &builder, &[\"bar\", \"a\", \"a/bar\"]);\n }\n\n #[test]\n fn gitignore() {\n let td = tmpdir();\n mkdirp(td.path().join(\".git\"));\n mkdirp(td.path().join(\"a\"));\n wfile(td.path().join(\".gitignore\"), \"foo\");\n wfile(td.path().join(\"foo\"), \"\");\n wfile(td.path().join(\"a/foo\"), \"\");\n wfile(td.path().join(\"bar\"), \"\");\n wfile(td.path().join(\"a/bar\"), \"\");\n\n assert_paths(\n td.path(),\n &WalkBuilder::new(td.path()),\n &[\"bar\", \"a\", \"a/bar\"],\n );\n }\n\n #[test]\n fn explicit_ignore() {\n let td = tmpdir();\n let igpath = td.path().join(\".not-an-ignore\");\n mkdirp(td.path().join(\"a\"));\n wfile(&igpath, \"foo\");\n wfile(td.path().join(\"foo\"), \"\");\n wfile(td.path().join(\"a/foo\"), \"\");\n wfile(td.path().join(\"bar\"), \"\");\n wfile(td.path().join(\"a/bar\"), \"\");\n\n let mut builder = WalkBuilder::new(td.path());\n assert!(builder.add_ignore(&igpath).is_none());\n assert_paths(td.path(), &builder, &[\"bar\", \"a\", \"a/bar\"]);\n }\n\n #[test]\n fn explicit_ignore_exclusive_use() {\n let td = tmpdir();\n let igpath = td.path().join(\".not-an-ignore\");\n mkdirp(td.path().join(\"a\"));\n wfile(&igpath, \"foo\");\n wfile(td.path().join(\"foo\"), \"\");\n wfile(td.path().join(\"a/foo\"), \"\");\n wfile(td.path().join(\"bar\"), \"\");\n wfile(td.path().join(\"a/bar\"), \"\");\n\n let mut builder = WalkBuilder::new(td.path());\n builder.standard_filters(false);\n assert!(builder.add_ignore(&igpath).is_none());\n assert_paths(\n td.path(),\n &builder,\n &[\".not-an-ignore\", \"bar\", \"a\", \"a/bar\"],\n );\n }\n\n #[test]\n fn gitignore_parent() {\n let td = tmpdir();\n mkdirp(td.path().join(\".git\"));\n mkdirp(td.path().join(\"a\"));\n wfile(td.path().join(\".gitignore\"), \"foo\");\n wfile(td.path().join(\"a/foo\"), \"\");\n wfile(td.path().join(\"a/bar\"), \"\");\n\n let root = td.path().join(\"a\");\n assert_paths(&root, &WalkBuilder::new(&root), &[\"bar\"]);\n }\n\n #[test]\n fn max_depth() {\n let td = tmpdir();\n mkdirp(td.path().join(\"a/b/c\"));\n wfile(td.path().join(\"foo\"), \"\");\n wfile(td.path().join(\"a/foo\"), \"\");\n wfile(td.path().join(\"a/b/foo\"), \"\");\n wfile(td.path().join(\"a/b/c/foo\"), \"\");\n\n let mut builder = WalkBuilder::new(td.path());\n assert_paths(\n td.path(),\n &builder,\n &[\"a\", \"a/b\", \"a/b/c\", \"foo\", \"a/foo\", \"a/b/foo\", \"a/b/c/foo\"],\n );\n assert_paths(td.path(), builder.max_depth(Some(0)), &[]);\n assert_paths(td.path(), builder.max_depth(Some(1)), &[\"a\", \"foo\"]);\n assert_paths(\n td.path(),\n builder.max_depth(Some(2)),\n &[\"a\", \"a/b\", \"foo\", \"a/foo\"],\n );\n }\n\n #[test]\n fn max_depth_does_not_load_unreachable_ignore_files() {\n let td = tmpdir();\n let leaf = td.path().join(\"leaf\");\n mkdirp(&leaf);\n wfile(leaf.join(\".ignore\"), \"{invalid\\n\");\n\n let mut builder = WalkBuilder::new(td.path());\n builder.max_depth(Some(1));\n let entry = builder\n .build()\n .find_map(|result| {\n let entry = result.unwrap();\n (entry.path() == leaf).then_some(entry)\n })\n .unwrap();\n\n assert!(entry.error().is_none());\n assert_paths(td.path(), &builder, &[\"leaf\"]);\n }\n\n #[test]\n fn min_depth() {\n let td = tmpdir();\n mkdirp(td.path().join(\"a/b/c\"));\n wfile(td.path().join(\"foo\"), \"\");\n wfile(td.path().join(\"a/foo\"), \"\");\n wfile(td.path().join(\"a/b/foo\"), \"\");\n wfile(td.path().join(\"a/b/c/foo\"), \"\");\n\n let builder = WalkBuilder::new(td.path());\n assert_paths(\n td.path(),\n &builder,\n &[\"a\", \"a/b\", \"a/b/c\", \"foo\", \"a/foo\", \"a/b/foo\", \"a/b/c/foo\"],\n );\n let mut builder = WalkBuilder::new(td.path());\n assert_paths(\n td.path(),\n &builder.min_depth(Some(0)),\n &[\"a\", \"a/b\", \"a/b/c\", \"foo\", \"a/foo\", \"a/b/foo\", \"a/b/c/foo\"],\n );\n assert_paths(\n td.path(),\n &builder.min_depth(Some(1)),\n &[\"a\", \"a/b\", \"a/b/c\", \"foo\", \"a/foo\", \"a/b/foo\", \"a/b/c/foo\"],\n );\n assert_paths(\n td.path(),\n builder.min_depth(Some(2)),\n &[\"a/b\", \"a/b/c\", \"a/b/c/foo\", \"a/b/foo\", \"a/foo\"],\n );\n assert_paths(\n td.path(),\n builder.min_depth(Some(3)),\n &[\"a/b/c\", \"a/b/c/foo\", \"a/b/foo\"],\n );\n assert_paths(td.path(), builder.min_depth(Some(10)), &[]);\n\n assert_paths(\n td.path(),\n builder.min_depth(Some(2)).max_depth(Some(1)),\n &[\"a/b\", \"a/foo\"],\n );\n }\n\n #[test]\n fn max_filesize() {\n let td = tmpdir();\n mkdirp(td.path().join(\"a/b\"));\n wfile_size(td.path().join(\"foo\"), 0);\n wfile_size(td.path().join(\"bar\"), 400);\n wfile_size(td.path().join(\"baz\"), 600);\n wfile_size(td.path().join(\"a/foo\"), 600);\n wfile_size(td.path().join(\"a/bar\"), 500);\n wfile_size(td.path().join(\"a/baz\"), 200);\n\n let mut builder = WalkBuilder::new(td.path());\n assert_paths(\n td.path(),\n &builder,\n &[\"a\", \"a/b\", \"foo\", \"bar\", \"baz\", \"a/foo\", \"a/bar\", \"a/baz\"],\n );\n assert_paths(\n td.path(),\n builder.max_filesize(Some(0)),\n &[\"a\", \"a/b\", \"foo\"],\n );\n assert_paths(\n td.path(),\n builder.max_filesize(Some(500)),\n &[\"a\", \"a/b\", \"foo\", \"bar\", \"a/bar\", \"a/baz\"],\n );\n assert_paths(\n td.path(),\n builder.max_filesize(Some(50000)),\n &[\"a\", \"a/b\", \"foo\", \"bar\", \"baz\", \"a/foo\", \"a/bar\", \"a/baz\"],\n );\n }\n\n #[cfg(unix)] // because symlinks on windows are weird\n #[test]\n fn symlinks() {\n let td = tmpdir();\n mkdirp(td.path().join(\"a/b\"));\n symlink(td.path().join(\"a/b\"), td.path().join(\"z\"));\n wfile(td.path().join(\"a/b/foo\"), \"\");\n\n let mut builder = WalkBuilder::new(td.path());\n assert_paths(td.path(), &builder, &[\"a\", \"a/b\", \"a/b/foo\", \"z\"]);\n assert_paths(\n td.path(),\n &builder.follow_links(true),\n &[\"a\", \"a/b\", \"a/b/foo\", \"z\", \"z/foo\"],\n );\n }\n\n #[cfg(unix)] // because symlinks on windows are weird\n #[test]\n fn first_path_not_symlink() {\n let td = tmpdir();\n mkdirp(td.path().join(\"foo\"));\n\n let dents = WalkBuilder::new(td.path().join(\"foo\"))\n .build()\n .into_iter()\n .collect::, _>>()\n .unwrap();\n assert_eq!(1, dents.len());\n assert!(!dents[0].path_is_symlink());\n\n let dents = walk_collect_entries_parallel(&WalkBuilder::new(\n td.path().join(\"foo\"),\n ));\n assert_eq!(1, dents.len());\n assert!(!dents[0].path_is_symlink());\n }\n\n #[cfg(unix)] // because symlinks on windows are weird\n #[test]\n fn symlink_loop() {\n let td = tmpdir();\n mkdirp(td.path().join(\"a/b\"));\n symlink(td.path().join(\"a\"), td.path().join(\"a/b/c\"));\n\n let mut builder = WalkBuilder::new(td.path());\n assert_paths(td.path(), &builder, &[\"a\", \"a/b\", \"a/b/c\"]);\n assert_paths(td.path(), &builder.follow_links(true), &[\"a\", \"a/b\"]);\n }\n\n // It's a little tricky to test the 'same_file_system' option since\n // we need an environment with more than one file system. We adopt a\n // heuristic where /sys is typically a distinct volume on Linux and roll\n // with that.\n #[test]\n #[cfg(target_os = \"linux\")]\n fn same_file_system() {\n use super::device_num;\n\n // If for some reason /sys doesn't exist or isn't a directory, just\n // skip this test.\n if !Path::new(\"/sys\").is_dir() {\n return;\n }\n\n // If our test directory actually isn't a different volume from /sys,\n // then this test is meaningless and we shouldn't run it.\n let td = tmpdir();\n if device_num(td.path()).unwrap() == device_num(\"/sys\").unwrap() {\n return;\n }\n\n mkdirp(td.path().join(\"same_file\"));\n symlink(\"/sys\", td.path().join(\"same_file\").join(\"alink\"));\n\n // Create a symlink to sys and enable following symlinks. If the\n // same_file_system option doesn't work, then this probably will hit a\n // permission error. Otherwise, it should just skip over the symlink\n // completely.\n let mut builder = WalkBuilder::new(td.path());\n builder.follow_links(true).same_file_system(true);\n assert_paths(td.path(), &builder, &[\"same_file\", \"same_file/alink\"]);\n }\n\n #[cfg(target_os = \"linux\")]\n #[test]\n fn no_read_permissions() {\n let dir_path = Path::new(\"/root\");\n\n // There's no /etc/sudoers.d, skip the test.\n if !dir_path.is_dir() {\n return;\n }\n // We're the root, so the test won't check what we want it to.\n if fs::read_dir(&dir_path).is_ok() {\n return;\n }\n\n // Check that we can't descend but get an entry for the parent dir.\n let builder = WalkBuilder::new(&dir_path);\n assert_paths(dir_path.parent().unwrap(), &builder, &[\"root\"]);\n }\n\n #[test]\n fn filter() {\n let td = tmpdir();\n mkdirp(td.path().join(\"a/b/c\"));\n mkdirp(td.path().join(\"x/y\"));\n wfile(td.path().join(\"a/b/foo\"), \"\");\n wfile(td.path().join(\"x/y/foo\"), \"\");\n\n assert_paths(\n td.path(),\n &WalkBuilder::new(td.path()),\n &[\"x\", \"x/y\", \"x/y/foo\", \"a\", \"a/b\", \"a/b/foo\", \"a/b/c\"],\n );\n\n assert_paths(\n td.path(),\n &WalkBuilder::new(td.path())\n .filter_entry(|entry| entry.file_name() != OsStr::new(\"a\")),\n &[\"x\", \"x/y\", \"x/y/foo\"],\n );\n }\n\n #[test]\n fn empty() {\n let td = tmpdir();\n assert_paths(td.path(), &WalkBuilder::empty(), &[]);\n\n let empty_paths: Vec<&OsStr> = Vec::new();\n assert_paths(td.path(), &WalkBuilder::from_iter(empty_paths), &[]);\n }\n\n #[test]\n fn from_iter() {\n let td = tmpdir();\n mkdirp(td.path().join(\"a/b/c\"));\n mkdirp(td.path().join(\"d/e/f\"));\n mkdirp(td.path().join(\"x/y\"));\n wfile(td.path().join(\"a/b/foo\"), \"\");\n wfile(td.path().join(\"d/e/f/foo\"), \"\");\n wfile(td.path().join(\"x/y/foo\"), \"\");\n\n let paths = vec![\n td.path().join(\"a\"),\n td.path().join(\"d\"),\n td.path().join(\"x\"),\n ];\n\n assert_paths(\n td.path(),\n &WalkBuilder::from_iter(paths),\n &[\n \"x\",\n \"x/y\",\n \"x/y/foo\",\n \"d\",\n \"d/e\",\n \"d/e/f\",\n \"d/e/f/foo\",\n \"a\",\n \"a/b\",\n \"a/b/foo\",\n \"a/b/c\",\n ],\n );\n }\n\n // This should always panic and never hang.\n //\n // Ref: https://github.com/BurntSushi/ripgrep/issues/3009\n #[test]\n #[should_panic]\n fn panic_in_parallel() {\n let td = tmpdir();\n wfile(td.path().join(\"foo.txt\"), \"\");\n\n WalkBuilder::new(td.path())\n .threads(40)\n .build_parallel()\n .run(|| Box::new(|_| panic!(\"oops!\")));\n }\n\n // This should always panic and never hang. The first call to the visitor\n // builder is used while processing the root paths. Previously, a panic on\n // the third call occurred after the first worker had already been spawned,\n // leaving it waiting indefinitely for workers that were never created.\n #[test]\n #[should_panic(expected = \"builder panic\")]\n fn panic_in_parallel_builder() {\n let td = tmpdir();\n wfile(td.path().join(\"foo.txt\"), \"\");\n\n let mut builds = 0;\n WalkBuilder::new(td.path()).threads(2).build_parallel().run(|| {\n builds += 1;\n if builds == 3 {\n panic!(\"builder panic\");\n }\n Box::new(|_| WalkState::Continue)\n });\n }\n}", "messages": null, "tools": null} {"id": "7cc3f8271c062356", "category": "code", "domain": "code", "source": "flask", "license": "BSD-3-Clause", "license_url": "https://spdx.org/licenses/BSD-3-Clause.html", "path": "tests/test_apps/blueprintapp/apps/frontend/__init__.py", "lang": "python", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/pallets/flask", "commit": "6a2f545bfd8ed31e19066a299296917e034aca58", "collector": "tools/harvest.py"}, "chars": 326, "sha256": "57c7465848d5c8719904da58cc3c4f18db75eb6b2b913e057339f56f1fa75a23", "text": "from flask import Blueprint\nfrom flask import render_template\n\nfrontend = Blueprint(\"frontend\", __name__, template_folder=\"templates\")\n\n\n@frontend.route(\"/\")\ndef index():\n return render_template(\"frontend/index.html\")\n\n\n@frontend.route(\"/missing\")\ndef missing_template():\n return render_template(\"missing_template.html\")", "messages": null, "tools": null} {"id": "7d38257126fcea2a", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/node/server/ws.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 14561, "sha256": "1684ff4a4eec51c1acc12d70228588dc8f9ac9aeac870a7da15372717369519c", "text": "import path from 'node:path'\nimport type { IncomingMessage, Server } from 'node:http'\nimport { STATUS_CODES, createServer as createHttpServer } from 'node:http'\nimport type { ServerOptions as HttpsServerOptions } from 'node:https'\nimport { createServer as createHttpsServer } from 'node:https'\nimport type { Socket } from 'node:net'\nimport type { Duplex } from 'node:stream'\nimport crypto from 'node:crypto'\nimport colors from 'picocolors'\nimport type { WebSocket as WebSocketRaw } from 'ws'\nimport { WebSocketServer as WebSocketServerRaw_ } from 'ws'\nimport { isHostAllowed } from 'host-validation-middleware'\nimport type { WebSocket as WebSocketTypes } from '#dep-types/ws'\nimport type {\n ErrorPayload,\n FullReloadPayload,\n HotPayload,\n} from '#types/hmrPayload'\nimport type { InferCustomEventPayload } from '#types/customEvent'\nimport type { ResolvedConfig } from '..'\nimport { isObject } from '../utils'\nimport type { NormalizedHotChannel, NormalizedHotChannelClient } from './hmr'\nimport { normalizeHotChannel } from './hmr'\nimport type { HttpServer } from '.'\n\n/* In Bun, the `ws` module is overridden to hook into the native code. Using the bundled `js` version\n * of `ws` will not work as Bun's req.socket does not allow reading/writing to the underlying socket.\n */\nconst WebSocketServerRaw = process.versions.bun\n ? // @ts-expect-error: Bun defines `import.meta.require`\n import.meta.require('ws').WebSocketServer\n : WebSocketServerRaw_\n\nexport const HMR_HEADER = 'vite-hmr'\n\nexport type WebSocketCustomListener = (\n data: T,\n client: WebSocketClient,\n) => void\n\nexport const isWebSocketServer: unique symbol = Symbol('isWebSocketServer')\n\nexport interface WebSocketServer extends NormalizedHotChannel {\n /**\n * Handle custom event emitted by `import.meta.hot.send`\n */\n on: WebSocketTypes.Server['on'] & {\n (\n event: T,\n listener: WebSocketCustomListener>,\n ): void\n }\n /**\n * Unregister event listener.\n */\n off: WebSocketTypes.Server['off'] & {\n (event: string, listener: Function): void\n }\n /**\n * Listen on port and host\n */\n listen(): void\n /**\n * Disconnect all clients and terminate the server.\n */\n close(): Promise\n\n [isWebSocketServer]: true\n /**\n * Get all connected clients.\n */\n clients: Set\n}\n\nexport interface WebSocketClient extends NormalizedHotChannelClient {\n /**\n * The raw WebSocket instance\n * @advanced\n */\n socket: WebSocketTypes\n}\n\nconst wsServerEvents = [\n 'connection',\n 'error',\n 'headers',\n 'listening',\n 'message',\n]\n\nfunction noop() {\n // noop\n}\n\n// we only allow websockets to be connected if it has a valid token\n// this is to prevent untrusted origins to connect to the server\n// for example, Cross-site WebSocket hijacking\n//\n// we should check the token before calling wss.handleUpgrade\n// otherwise untrusted ws clients will be included in wss.clients\n//\n// using the query params means the token might be logged out in server or middleware logs\n// but we assume that is not an issue since the token is regenerated for each process\nfunction hasValidToken(config: ResolvedConfig, url: URL) {\n const token = url.searchParams.get('token')\n if (!token) return false\n\n try {\n const isValidToken = crypto.timingSafeEqual(\n Buffer.from(token),\n Buffer.from(config.webSocketToken),\n )\n return isValidToken\n } catch {} // an error is thrown when the length is incorrect\n return false\n}\n\nexport function createWebSocketServer(\n server: HttpServer | null,\n config: ResolvedConfig,\n httpsOptions?: HttpsServerOptions,\n): WebSocketServer {\n if (config.server.ws === false) {\n return {\n [isWebSocketServer]: true,\n get clients() {\n return new Set()\n },\n async close() {\n // noop\n },\n on: noop as any as WebSocketServer['on'],\n off: noop as any as WebSocketServer['off'],\n setInvokeHandler: noop,\n handleInvoke: async () => ({\n error: {\n name: 'TransportError',\n message: 'handleInvoke not implemented',\n stack: new Error().stack,\n },\n }),\n listen: noop,\n send: noop,\n }\n }\n\n let wsHttpServer: Server | undefined = undefined\n\n const wsOptions = isObject(config.server.ws) ? config.server.ws : undefined\n const wsCustomServer = wsOptions?.server\n const wsPort = wsOptions?.port\n // TODO: the main server port may not have been chosen yet as it may use the next available\n const portsAreCompatible = !wsPort || wsPort === config.server.port\n const wsServer = wsCustomServer || (portsAreCompatible && server)\n let hmrServerWsListener: (\n req: InstanceType,\n socket: Duplex,\n head: Buffer,\n ) => void\n const customListeners = new Map>>()\n const clientsMap = new WeakMap()\n const port = wsPort || 24678\n const host = wsOptions?.host || undefined\n const allowedHosts =\n config.server.allowedHosts === true\n ? config.server.allowedHosts\n : Object.freeze([...config.server.allowedHosts]) // Freeze the array to allow caching\n\n const shouldHandle = (req: IncomingMessage) => {\n const protocol = req.headers['sec-websocket-protocol']!\n // vite-ping is allowed to connect from anywhere\n // because it needs to be connected before the client fetches the new `/@vite/client`\n // this is fine because vite-ping does not receive / send any meaningful data\n if (protocol === 'vite-ping') return true\n\n if (\n allowedHosts !== true &&\n !isHostAllowed(req.headers.host, allowedHosts)\n ) {\n return false\n }\n\n if (config.legacy?.skipWebSocketTokenCheck) {\n return true\n }\n\n // If the Origin header is set, this request might be coming from a browser.\n // Browsers always sets the Origin header for WebSocket connections.\n if (req.headers.origin) {\n const parsedUrl = new URL(`http://example.com${req.url!}`)\n return hasValidToken(config, parsedUrl)\n }\n\n // We allow non-browser requests to connect without a token\n // for backward compat and convenience\n // This is fine because if you can sent a request without the SOP limitation,\n // you can also send a normal HTTP request to the server.\n return true\n }\n const handleUpgrade = (\n req: IncomingMessage,\n socket: Duplex,\n head: Buffer,\n isPing: boolean,\n ) => {\n wss.handleUpgrade(req, socket as Socket, head, (ws) => {\n // vite-ping is allowed to connect from anywhere\n // we close the connection immediately without connection event\n // so that the client does not get included in `wss.clients`\n if (isPing) {\n ws.close(/* Normal Closure */ 1000)\n return\n }\n wss.emit('connection', ws, req)\n })\n }\n const wss: WebSocketServerRaw_ = new WebSocketServerRaw({ noServer: true })\n wss.shouldHandle = shouldHandle\n\n if (wsServer) {\n let hmrBase = config.base\n const wsPath = wsOptions?.path\n if (wsPath) {\n hmrBase = path.posix.join(hmrBase, wsPath)\n }\n hmrServerWsListener = (req, socket, head) => {\n const protocol = req.headers['sec-websocket-protocol']!\n const parsedUrl = new URL(`http://example.com${req.url!}`)\n if (\n [HMR_HEADER, 'vite-ping'].includes(protocol) &&\n parsedUrl.pathname === hmrBase\n ) {\n handleUpgrade(req, socket as Socket, head, protocol === 'vite-ping')\n }\n }\n wsServer.on('upgrade', hmrServerWsListener)\n } else {\n // http server request handler keeps the same with\n // https://github.com/websockets/ws/blob/45e17acea791d865df6b255a55182e9c42e5877a/lib/websocket-server.js#L88-L96\n const route = ((_, res) => {\n const statusCode = 426\n const body = STATUS_CODES[statusCode]\n if (!body)\n throw new Error(`No body text found for the ${statusCode} status code`)\n\n res.writeHead(statusCode, {\n 'Content-Length': body.length,\n 'Content-Type': 'text/plain',\n })\n res.end(body)\n }) as Parameters[1]\n // vite dev server in middleware mode\n // need to call ws listen manually\n if (httpsOptions) {\n wsHttpServer = createHttpsServer(httpsOptions, route)\n } else {\n wsHttpServer = createHttpServer(route)\n }\n wsHttpServer.on('upgrade', (req, socket, head) => {\n const protocol = req.headers['sec-websocket-protocol']!\n if (protocol === 'vite-ping' && server && !server.listening) {\n // reject connection to tell the vite/client that the server is not ready\n // if the http server is not listening\n // because the ws server listens before the http server listens\n req.destroy()\n return\n }\n handleUpgrade(req, socket as Socket, head, protocol === 'vite-ping')\n })\n wsHttpServer.on('error', (e: Error & { code: string; port: number }) => {\n if (e.code === 'EADDRINUSE') {\n config.logger.error(\n colors.red(\n `WebSocket server error: Port ${e.port} is already in use`,\n ),\n { error: e },\n )\n } else {\n config.logger.error(\n colors.red(`WebSocket server error:\\n${e.stack || e.message}`),\n { error: e },\n )\n }\n })\n }\n\n const emitCustomEvent = (\n event: T,\n data: InferCustomEventPayload,\n socket: WebSocketRaw,\n ) => {\n const listeners = customListeners.get(event)\n if (!listeners?.size) return\n\n const client = getSocketClient(socket)\n for (const listener of listeners) {\n listener(data, client)\n }\n }\n\n wss.on('connection', (socket) => {\n socket.on('message', (raw) => {\n if (!customListeners.size) return\n let parsed: any\n try {\n parsed = JSON.parse(String(raw))\n } catch {}\n if (!parsed || parsed.type !== 'custom' || !parsed.event) return\n emitCustomEvent(parsed.event, parsed.data, socket)\n })\n socket.on('error', (err) => {\n config.logger.error(`${colors.red(`ws error:`)}\\n${err.stack}`, {\n timestamp: true,\n error: err,\n })\n })\n socket.on('close', () => {\n emitCustomEvent('vite:client:disconnect', undefined, socket)\n })\n\n emitCustomEvent('vite:client:connect', undefined, socket)\n\n socket.send(JSON.stringify({ type: 'connected' }))\n if (bufferedMessage) {\n socket.send(JSON.stringify(bufferedMessage))\n bufferedMessage = null\n }\n })\n\n wss.on('error', (e: Error & { code: string; port: number }) => {\n if (e.code === 'EADDRINUSE') {\n config.logger.error(\n colors.red(`WebSocket server error: Port ${e.port} is already in use`),\n { error: e },\n )\n } else {\n config.logger.error(\n colors.red(`WebSocket server error:\\n${e.stack || e.message}`),\n { error: e },\n )\n }\n })\n\n // Provide a wrapper to the ws client so we can send messages in JSON format\n // To be consistent with server.ws.send\n function getSocketClient(socket: WebSocketRaw) {\n if (!clientsMap.has(socket)) {\n clientsMap.set(socket, {\n send: (...args: any[]) => {\n let payload: HotPayload\n if (typeof args[0] === 'string') {\n payload = {\n type: 'custom',\n event: args[0],\n data: args[1],\n }\n } else {\n payload = args[0]\n }\n socket.send(JSON.stringify(payload))\n },\n socket,\n })\n }\n return clientsMap.get(socket)!\n }\n\n // On page reloads, if a file fails to compile and returns 500, the server\n // sends the error payload before the client connection is established.\n // If we have no open clients, buffer the error and send it to the next\n // connected client.\n // The same thing may happen when the optimizer runs fast enough to\n // finish the bundling before the client connects.\n let bufferedMessage: ErrorPayload | FullReloadPayload | null = null\n\n const normalizedHotChannel = normalizeHotChannel(\n {\n send(payload) {\n if (\n (payload.type === 'error' || payload.type === 'full-reload') &&\n !wss.clients.size\n ) {\n bufferedMessage = payload\n return\n }\n\n const stringified = JSON.stringify(payload)\n wss.clients.forEach((client) => {\n // readyState 1 means the connection is open\n if (client.readyState === 1) {\n client.send(stringified)\n }\n })\n },\n on(event: string, fn: any) {\n if (!customListeners.has(event)) {\n customListeners.set(event, new Set())\n }\n customListeners.get(event)!.add(fn)\n },\n off(event: string, fn: any) {\n customListeners.get(event)?.delete(fn)\n },\n listen() {\n wsHttpServer?.listen(port, host)\n },\n close() {\n // should remove listener if hmr.server is set\n // otherwise the old listener swallows all WebSocket connections\n if (hmrServerWsListener && wsServer) {\n wsServer.off('upgrade', hmrServerWsListener)\n }\n return new Promise((resolve, reject) => {\n wss.clients.forEach((client) => {\n client.terminate()\n })\n wss.close((err) => {\n if (err) {\n reject(err)\n } else {\n if (wsHttpServer) {\n wsHttpServer.close((err) => {\n if (err) {\n reject(err)\n } else {\n resolve()\n }\n })\n } else {\n resolve()\n }\n }\n })\n })\n },\n },\n config.server.hmr !== false,\n // Don't normalize client as we already handles the send, and to keep `.socket`\n false,\n )\n return {\n ...normalizedHotChannel,\n\n on: ((event: string, fn: any) => {\n if (wsServerEvents.includes(event)) {\n wss.on(event, fn)\n return\n }\n normalizedHotChannel.on(event, fn)\n }) as WebSocketServer['on'],\n off: ((event: string, fn: any) => {\n if (wsServerEvents.includes(event)) {\n wss.off(event, fn)\n return\n }\n normalizedHotChannel.off(event, fn)\n }) as WebSocketServer['off'],\n async close() {\n await normalizedHotChannel.close()\n },\n\n [isWebSocketServer]: true,\n get clients() {\n return new Set(Array.from(wss.clients).map(getSocketClient))\n },\n }\n}", "messages": null, "tools": null} {"id": "7e1be1468dc68b2b", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/legacy/__tests__/legacy.spec.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 7314, "sha256": "c91d7648c58b0c239d08fc02e11770834a3aa38eff3778c463770662cd0a1d01", "text": "import { describe, expect, test } from 'vitest'\nimport {\n findAssetFile,\n getColor,\n isBuild,\n isBundled,\n isBundledDev,\n listAssets,\n page,\n readFile,\n readManifest,\n} from '~utils'\n\ntest('should load the worker', async () => {\n await expect.poll(() => page.textContent('.worker-message')).toMatch('module')\n})\n\ntest('should work', async () => {\n await expect.poll(() => page.textContent('#app')).toMatch('Hello')\n})\n\n// bundled dev: import.meta.env.LEGACY is not replaced — needs a fix in vite's\n// legacy-env define handling (vitejs/vite#23028)\ntest.skipIf(isBundledDev)('import.meta.env.LEGACY', async () => {\n await expect\n .poll(() => page.textContent('#env'))\n .toMatch(isBuild ? 'true' : 'false')\n await expect.poll(() => page.textContent('#env-equal')).toMatch('true')\n})\n\n// https://github.com/vitejs/vite/issues/3400\ntest('transpiles down iterators correctly', async () => {\n await expect.poll(() => page.textContent('#iterators')).toMatch('hello')\n})\n\ntest('async generator', async () => {\n await expect\n .poll(() => page.textContent('#async-generator'))\n .toMatch('[0,1,2]')\n})\n\ntest('wraps with iife', async () => {\n await expect\n .poll(() => page.textContent('#babel-helpers'))\n .toMatch('exposed babel helpers: false')\n})\n\ntest('generates assets', async () => {\n await expect\n .poll(() => page.textContent('#assets'))\n .toMatch(\n isBuild\n ? [\n 'index: text/html',\n 'index-legacy: text/html',\n 'chunk-async: text/html',\n 'chunk-async-legacy: text/html',\n 'immutable-chunk: text/javascript',\n 'immutable-chunk-legacy: text/javascript',\n 'polyfills-legacy: text/html',\n ].join('\\n')\n : isBundledDev\n ? [\n // bundled dev serves the entry at /assets/index.js. That name\n // has no hash, so the request finds it and gets JavaScript.\n // Legacy chunks do not exist at all, because the legacy plugin\n // only runs on build.\n // Every other chunk name has a hash. A request for the plain\n // name finds nothing and falls back to index.html.\n // `immutable-chunk` gets a hash here too, because the dev bundle\n // ignores `build.rolldownOptions.output` naming. Whether it\n // should ignore it is still undecided (vitejs/vite#23028).\n 'index: text/javascript',\n 'index-legacy: text/html',\n 'chunk-async: text/html',\n 'chunk-async-legacy: text/html',\n 'immutable-chunk: text/html',\n 'immutable-chunk-legacy: text/html',\n 'polyfills-legacy: text/html',\n ].join('\\n')\n : [\n 'index: text/html',\n 'index-legacy: text/html',\n 'chunk-async: text/html',\n 'chunk-async-legacy: text/html',\n 'immutable-chunk: text/html',\n 'immutable-chunk-legacy: text/html',\n 'polyfills-legacy: text/html',\n ].join('\\n'),\n )\n})\n\ntest('correctly emits styles', async () => {\n expect(await getColor('#app')).toBe('red')\n})\n\n// dynamic import css\ntest('should load dynamic import with css', async () => {\n await page.click('#dynamic-css-button')\n await expect.poll(() => getColor('#dynamic-css')).toBe('red')\n})\n\ntest('asset url', async () => {\n expect(await page.textContent('#asset-path')).toMatch(\n isBundled ? /\\/assets\\/vite-[-\\w]+\\.svg/ : '/vite.svg',\n )\n})\n\ndescribe.runIf(isBuild)('build', () => {\n test('should generate correct manifest', async () => {\n const manifest = readManifest()\n // legacy polyfill\n expect(manifest['../../vite/legacy-polyfills-legacy']).toBeDefined()\n expect(manifest['../../vite/legacy-polyfills-legacy'].src).toBe(\n '../../vite/legacy-polyfills-legacy',\n )\n expect(manifest['custom0-legacy.js'].file).toMatch(\n /chunk-X-legacy\\.[-\\w]{8}.js/,\n )\n expect(manifest['custom1-legacy.js'].file).toMatch(\n /chunk-X-legacy-[-\\w]{8}.js/,\n )\n expect(manifest['custom2-legacy.js'].file).toMatch(\n /chunk-X-legacy[-\\w]{8}.js/,\n )\n // modern polyfill\n expect(manifest['../../vite/legacy-polyfills']).toBeDefined()\n expect(manifest['../../vite/legacy-polyfills'].src).toBe(\n '../../vite/legacy-polyfills',\n )\n })\n\n test('should minify legacy chunks', async () => {\n // This is a ghetto heuristic, but Oxc output seems to reliably include\n // this code\n const terserPattern = /,function\\(e,/\n\n expect(findAssetFile(/chunk-async-legacy/)).toMatch(terserPattern)\n expect(findAssetFile(/chunk-async(?!-legacy)/)).not.toMatch(terserPattern)\n expect(findAssetFile(/immutable-chunk-legacy/)).toMatch(terserPattern)\n expect(findAssetFile(/immutable-chunk(?!-legacy)/)).not.toMatch(\n terserPattern,\n )\n expect(findAssetFile(/index-legacy/)).toMatch(terserPattern)\n expect(findAssetFile(/index(?!-legacy)/)).not.toMatch(terserPattern)\n expect(findAssetFile(/polyfills-legacy/)).toMatch(terserPattern)\n })\n\n test('should not use newer syntax when minifying legacy chunks', () => {\n // The playground targets IE 11, so babel lowers the legacy chunks to ES5.\n // The minifier must not reintroduce syntax newer than its `es2015` compress\n // target: `try {} catch (e) {}` must not be collapsed to `try {} catch {}`\n // (ES2019) and optional chaining (ES2020) must not appear.\n const mainLegacyChunk = findAssetFile(/chunk-main-legacy/)\n expect(mainLegacyChunk).toMatch(/catch\\s*\\(/)\n expect(mainLegacyChunk).not.toMatch(/catch\\s*\\{/)\n expect(mainLegacyChunk).not.toMatch(/\\w\\?\\.\\w/)\n })\n\n test('should emit css file', async () => {\n expect(\n listAssets().some((filename) => filename.endsWith('.css')),\n ).toBeTruthy()\n })\n\n test('includes structuredClone polyfill which is supported after core-js v3', () => {\n expect(findAssetFile(/polyfills-legacy/)).toMatch('`structuredClone`')\n expect(findAssetFile(/polyfills-[-\\w]{8}\\./)).toMatch('`structuredClone`')\n })\n\n test('should generate legacy sourcemap file', async () => {\n expect(\n listAssets().some((filename) =>\n /chunk-main-legacy\\.[-\\w]{8}\\.js\\.map$/.test(filename),\n ),\n ).toBeTruthy()\n expect(\n listAssets().some((filename) =>\n /polyfills-legacy-[-\\w]{8}\\.js\\.map$/.test(filename),\n ),\n ).toBeTruthy()\n // also for modern polyfills\n expect(\n listAssets().some((filename) =>\n /polyfills-[-\\w]{8}\\.js\\.map$/.test(filename),\n ),\n ).toBeTruthy()\n })\n\n test('should have only modern entry files guarded', async () => {\n const guard = /(import\\s*\\()|(import.meta)|(async\\s*function\\*)/\n expect(findAssetFile(/index(?!-legacy)/)).toMatch(guard)\n expect(findAssetFile(/polyfills(?!-legacy)/)).toMatch(guard)\n\n expect(findAssetFile(/chunk-async(?!-legacy)/)).not.toMatch(guard)\n expect(findAssetFile(/index-legacy/)).not.toMatch(guard)\n })\n\n test('should not include preload helper in legacy chunks', async () => {\n expect(\n listAssets().filter(\n (filename) =>\n filename.includes('-legacy') &&\n readFile(`dist/assets/${filename}`).includes('Unable to preload'),\n ),\n ).toStrictEqual([])\n })\n})", "messages": null, "tools": null} {"id": "7e5444a6fa99ab2c", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/thirdparty/Fuzzer/FuzzerDriver.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 18123, "sha256": "f45cdba7f520b98b6503ca0f213d6dff5f2e1b707c5d29f355fc1a54f90cc13a", "text": "//===- FuzzerDriver.cpp - FuzzerDriver function and flags -----------------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n// FuzzerDriver and flag parsing.\n//===----------------------------------------------------------------------===//\n\n#include \"FuzzerCorpus.h\"\n#include \"FuzzerInterface.h\"\n#include \"FuzzerInternal.h\"\n#include \"FuzzerIO.h\"\n#include \"FuzzerMutate.h\"\n#include \"FuzzerRandom.h\"\n#include \"FuzzerTracePC.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n// This function should be present in the libFuzzer so that the client\n// binary can test for its existence.\nextern \"C\" __attribute__((used)) void __libfuzzer_is_present() {}\n\nnamespace fuzzer {\n\n// Program arguments.\nstruct FlagDescription {\n const char *Name;\n const char *Description;\n int Default;\n int *IntFlag;\n const char **StrFlag;\n unsigned int *UIntFlag;\n};\n\nstruct {\n#define FUZZER_DEPRECATED_FLAG(Name)\n#define FUZZER_FLAG_INT(Name, Default, Description) int Name;\n#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) unsigned int Name;\n#define FUZZER_FLAG_STRING(Name, Description) const char *Name;\n#include \"FuzzerFlags.def\"\n#undef FUZZER_DEPRECATED_FLAG\n#undef FUZZER_FLAG_INT\n#undef FUZZER_FLAG_UNSIGNED\n#undef FUZZER_FLAG_STRING\n} Flags;\n\nstatic const FlagDescription FlagDescriptions [] {\n#define FUZZER_DEPRECATED_FLAG(Name) \\\n {#Name, \"Deprecated; don't use\", 0, nullptr, nullptr, nullptr},\n#define FUZZER_FLAG_INT(Name, Default, Description) \\\n {#Name, Description, Default, &Flags.Name, nullptr, nullptr},\n#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) \\\n {#Name, Description, static_cast(Default), \\\n nullptr, nullptr, &Flags.Name},\n#define FUZZER_FLAG_STRING(Name, Description) \\\n {#Name, Description, 0, nullptr, &Flags.Name, nullptr},\n#include \"FuzzerFlags.def\"\n#undef FUZZER_DEPRECATED_FLAG\n#undef FUZZER_FLAG_INT\n#undef FUZZER_FLAG_UNSIGNED\n#undef FUZZER_FLAG_STRING\n};\n\nstatic const size_t kNumFlags =\n sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]);\n\nstatic std::vector *Inputs;\nstatic std::string *ProgName;\n\nstatic void PrintHelp() {\n Printf(\"Usage:\\n\");\n auto Prog = ProgName->c_str();\n Printf(\"\\nTo run fuzzing pass 0 or more directories.\\n\");\n Printf(\"%s [-flag1=val1 [-flag2=val2 ...] ] [dir1 [dir2 ...] ]\\n\", Prog);\n\n Printf(\"\\nTo run individual tests without fuzzing pass 1 or more files:\\n\");\n Printf(\"%s [-flag1=val1 [-flag2=val2 ...] ] file1 [file2 ...]\\n\", Prog);\n\n Printf(\"\\nFlags: (strictly in form -flag=value)\\n\");\n size_t MaxFlagLen = 0;\n for (size_t F = 0; F < kNumFlags; F++)\n MaxFlagLen = std::max(strlen(FlagDescriptions[F].Name), MaxFlagLen);\n\n for (size_t F = 0; F < kNumFlags; F++) {\n const auto &D = FlagDescriptions[F];\n if (strstr(D.Description, \"internal flag\") == D.Description) continue;\n Printf(\" %s\", D.Name);\n for (size_t i = 0, n = MaxFlagLen - strlen(D.Name); i < n; i++)\n Printf(\" \");\n Printf(\"\\t\");\n Printf(\"%d\\t%s\\n\", D.Default, D.Description);\n }\n Printf(\"\\nFlags starting with '--' will be ignored and \"\n \"will be passed verbatim to subprocesses.\\n\");\n}\n\nstatic const char *FlagValue(const char *Param, const char *Name) {\n size_t Len = strlen(Name);\n if (Param[0] == '-' && strstr(Param + 1, Name) == Param + 1 &&\n Param[Len + 1] == '=')\n return &Param[Len + 2];\n return nullptr;\n}\n\n// Avoid calling stol as it triggers a bug in clang/glibc build.\nstatic long MyStol(const char *Str) {\n long Res = 0;\n long Sign = 1;\n if (*Str == '-') {\n Str++;\n Sign = -1;\n }\n for (size_t i = 0; Str[i]; i++) {\n char Ch = Str[i];\n if (Ch < '0' || Ch > '9')\n return Res;\n Res = Res * 10 + (Ch - '0');\n }\n return Res * Sign;\n}\n\nstatic bool ParseOneFlag(const char *Param) {\n if (Param[0] != '-') return false;\n if (Param[1] == '-') {\n static bool PrintedWarning = false;\n if (!PrintedWarning) {\n PrintedWarning = true;\n Printf(\"INFO: libFuzzer ignores flags that start with '--'\\n\");\n }\n for (size_t F = 0; F < kNumFlags; F++)\n if (FlagValue(Param + 1, FlagDescriptions[F].Name))\n Printf(\"WARNING: did you mean '%s' (single dash)?\\n\", Param + 1);\n return true;\n }\n for (size_t F = 0; F < kNumFlags; F++) {\n const char *Name = FlagDescriptions[F].Name;\n const char *Str = FlagValue(Param, Name);\n if (Str) {\n if (FlagDescriptions[F].IntFlag) {\n int Val = MyStol(Str);\n *FlagDescriptions[F].IntFlag = Val;\n if (Flags.verbosity >= 2)\n Printf(\"Flag: %s %d\\n\", Name, Val);\n return true;\n } else if (FlagDescriptions[F].UIntFlag) {\n unsigned int Val = std::stoul(Str);\n *FlagDescriptions[F].UIntFlag = Val;\n if (Flags.verbosity >= 2)\n Printf(\"Flag: %s %u\\n\", Name, Val);\n return true;\n } else if (FlagDescriptions[F].StrFlag) {\n *FlagDescriptions[F].StrFlag = Str;\n if (Flags.verbosity >= 2)\n Printf(\"Flag: %s %s\\n\", Name, Str);\n return true;\n } else { // Deprecated flag.\n Printf(\"Flag: %s: deprecated, don't use\\n\", Name);\n return true;\n }\n }\n }\n Printf(\"\\n\\nWARNING: unrecognized flag '%s'; \"\n \"use -help=1 to list all flags\\n\\n\", Param);\n return true;\n}\n\n// We don't use any library to minimize dependencies.\nstatic void ParseFlags(const std::vector &Args) {\n for (size_t F = 0; F < kNumFlags; F++) {\n if (FlagDescriptions[F].IntFlag)\n *FlagDescriptions[F].IntFlag = FlagDescriptions[F].Default;\n if (FlagDescriptions[F].UIntFlag)\n *FlagDescriptions[F].UIntFlag =\n static_cast(FlagDescriptions[F].Default);\n if (FlagDescriptions[F].StrFlag)\n *FlagDescriptions[F].StrFlag = nullptr;\n }\n Inputs = new std::vector;\n for (size_t A = 1; A < Args.size(); A++) {\n if (ParseOneFlag(Args[A].c_str())) continue;\n Inputs->push_back(Args[A]);\n }\n}\n\nstatic std::mutex Mu;\n\nstatic void PulseThread() {\n while (true) {\n SleepSeconds(600);\n std::lock_guard Lock(Mu);\n Printf(\"pulse...\\n\");\n }\n}\n\nstatic void WorkerThread(const std::string &Cmd, std::atomic *Counter,\n unsigned NumJobs, std::atomic *HasErrors) {\n while (true) {\n unsigned C = (*Counter)++;\n if (C >= NumJobs) break;\n std::string Log = \"fuzz-\" + std::to_string(C) + \".log\";\n std::string ToRun = Cmd + \" > \" + Log + \" 2>&1\\n\";\n if (Flags.verbosity)\n Printf(\"%s\", ToRun.c_str());\n int ExitCode = ExecuteCommand(ToRun);\n if (ExitCode != 0)\n *HasErrors = true;\n std::lock_guard Lock(Mu);\n Printf(\"================== Job %u exited with exit code %d ============\\n\",\n C, ExitCode);\n fuzzer::CopyFileToErr(Log);\n }\n}\n\nstd::string CloneArgsWithoutX(const std::vector &Args,\n const char *X1, const char *X2) {\n std::string Cmd;\n for (auto &S : Args) {\n if (FlagValue(S.c_str(), X1) || FlagValue(S.c_str(), X2))\n continue;\n Cmd += S + \" \";\n }\n return Cmd;\n}\n\nstatic int RunInMultipleProcesses(const std::vector &Args,\n unsigned NumWorkers, unsigned NumJobs) {\n std::atomic Counter(0);\n std::atomic HasErrors(false);\n std::string Cmd = CloneArgsWithoutX(Args, \"jobs\", \"workers\");\n std::vector V;\n std::thread Pulse(PulseThread);\n Pulse.detach();\n for (unsigned i = 0; i < NumWorkers; i++)\n V.push_back(std::thread(WorkerThread, Cmd, &Counter, NumJobs, &HasErrors));\n for (auto &T : V)\n T.join();\n return HasErrors ? 1 : 0;\n}\n\nstatic void RssThread(Fuzzer *F, size_t RssLimitMb) {\n while (true) {\n SleepSeconds(1);\n size_t Peak = GetPeakRSSMb();\n if (Peak > RssLimitMb)\n F->RssLimitCallback();\n }\n}\n\nstatic void StartRssThread(Fuzzer *F, size_t RssLimitMb) {\n if (!RssLimitMb) return;\n std::thread T(RssThread, F, RssLimitMb);\n T.detach();\n}\n\nint RunOneTest(Fuzzer *F, const char *InputFilePath, size_t MaxLen) {\n Unit U = FileToVector(InputFilePath);\n if (MaxLen && MaxLen < U.size())\n U.resize(MaxLen);\n F->RunOne(U.data(), U.size());\n F->TryDetectingAMemoryLeak(U.data(), U.size(), true);\n return 0;\n}\n\nstatic bool AllInputsAreFiles() {\n if (Inputs->empty()) return false;\n for (auto &Path : *Inputs)\n if (!IsFile(Path))\n return false;\n return true;\n}\n\nint MinimizeCrashInput(const std::vector &Args) {\n if (Inputs->size() != 1) {\n Printf(\"ERROR: -minimize_crash should be given one input file\\n\");\n exit(1);\n }\n std::string InputFilePath = Inputs->at(0);\n std::string BaseCmd =\n CloneArgsWithoutX(Args, \"minimize_crash\", \"exact_artifact_path\");\n auto InputPos = BaseCmd.find(\" \" + InputFilePath + \" \");\n assert(InputPos != std::string::npos);\n BaseCmd.erase(InputPos, InputFilePath.size() + 1);\n if (Flags.runs <= 0 && Flags.max_total_time == 0) {\n Printf(\"INFO: you need to specify -runs=N or \"\n \"-max_total_time=N with -minimize_crash=1\\n\"\n \"INFO: defaulting to -max_total_time=600\\n\");\n BaseCmd += \" -max_total_time=600\";\n }\n // BaseCmd += \" > /dev/null 2>&1 \";\n\n std::string CurrentFilePath = InputFilePath;\n while (true) {\n Unit U = FileToVector(CurrentFilePath);\n if (U.size() < 2) {\n Printf(\"CRASH_MIN: '%s' is small enough\\n\", CurrentFilePath.c_str());\n return 0;\n }\n Printf(\"CRASH_MIN: minimizing crash input: '%s' (%zd bytes)\\n\",\n CurrentFilePath.c_str(), U.size());\n\n auto Cmd = BaseCmd + \" \" + CurrentFilePath;\n\n Printf(\"CRASH_MIN: executing: %s\\n\", Cmd.c_str());\n int ExitCode = ExecuteCommand(Cmd);\n if (ExitCode == 0) {\n Printf(\"ERROR: the input %s did not crash\\n\", CurrentFilePath.c_str());\n exit(1);\n }\n Printf(\"CRASH_MIN: '%s' (%zd bytes) caused a crash. Will try to minimize \"\n \"it further\\n\",\n CurrentFilePath.c_str(), U.size());\n\n std::string ArtifactPath = \"minimized-from-\" + Hash(U);\n Cmd += \" -minimize_crash_internal_step=1 -exact_artifact_path=\" +\n ArtifactPath;\n Printf(\"CRASH_MIN: executing: %s\\n\", Cmd.c_str());\n ExitCode = ExecuteCommand(Cmd);\n if (ExitCode == 0) {\n if (Flags.exact_artifact_path) {\n CurrentFilePath = Flags.exact_artifact_path;\n WriteToFile(U, CurrentFilePath);\n }\n Printf(\"CRASH_MIN: failed to minimize beyond %s (%d bytes), exiting\\n\",\n CurrentFilePath.c_str(), U.size());\n return 0;\n }\n CurrentFilePath = ArtifactPath;\n Printf(\"\\n\\n\\n\\n\\n\\n*********************************\\n\");\n }\n return 0;\n}\n\nint MinimizeCrashInputInternalStep(Fuzzer *F, InputCorpus *Corpus) {\n assert(Inputs->size() == 1);\n std::string InputFilePath = Inputs->at(0);\n Unit U = FileToVector(InputFilePath);\n assert(U.size() > 2);\n Printf(\"INFO: Starting MinimizeCrashInputInternalStep: %zd\\n\", U.size());\n Corpus->AddToCorpus(U, 0);\n F->SetMaxInputLen(U.size());\n F->SetMaxMutationLen(U.size() - 1);\n F->MinimizeCrashLoop(U);\n Printf(\"INFO: Done MinimizeCrashInputInternalStep, no crashes found\\n\");\n exit(0);\n return 0;\n}\n\nint FuzzerDriver(int *argc, char ***argv, UserCallback Callback) {\n using namespace fuzzer;\n assert(argc && argv && \"Argument pointers cannot be nullptr\");\n EF = new ExternalFunctions();\n if (EF->LLVMFuzzerInitialize)\n EF->LLVMFuzzerInitialize(argc, argv);\n const std::vector Args(*argv, *argv + *argc);\n assert(!Args.empty());\n ProgName = new std::string(Args[0]);\n ParseFlags(Args);\n if (Flags.help) {\n PrintHelp();\n return 0;\n }\n\n if (Flags.minimize_crash)\n return MinimizeCrashInput(Args);\n\n if (Flags.close_fd_mask & 2)\n DupAndCloseStderr();\n if (Flags.close_fd_mask & 1)\n CloseStdout();\n\n if (Flags.jobs > 0 && Flags.workers == 0) {\n Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);\n if (Flags.workers > 1)\n Printf(\"Running %u workers\\n\", Flags.workers);\n }\n\n if (Flags.workers > 0 && Flags.jobs > 0)\n return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);\n\n const size_t kMaxSaneLen = 1 << 20;\n const size_t kMinDefaultLen = 64;\n FuzzingOptions Options;\n Options.Verbosity = Flags.verbosity;\n Options.MaxLen = Flags.max_len;\n Options.UnitTimeoutSec = Flags.timeout;\n Options.ErrorExitCode = Flags.error_exitcode;\n Options.TimeoutExitCode = Flags.timeout_exitcode;\n Options.MaxTotalTimeSec = Flags.max_total_time;\n Options.DoCrossOver = Flags.cross_over;\n Options.MutateDepth = Flags.mutate_depth;\n Options.UseCounters = Flags.use_counters;\n Options.UseIndirCalls = Flags.use_indir_calls;\n Options.UseMemcmp = Flags.use_memcmp;\n Options.UseMemmem = Flags.use_memmem;\n Options.UseCmp = Flags.use_cmp;\n Options.UseValueProfile = Flags.use_value_profile;\n Options.Shrink = Flags.shrink;\n Options.ShuffleAtStartUp = Flags.shuffle;\n Options.PreferSmall = Flags.prefer_small;\n Options.ReloadIntervalSec = Flags.reload;\n Options.OnlyASCII = Flags.only_ascii;\n Options.OutputCSV = Flags.output_csv;\n Options.DetectLeaks = Flags.detect_leaks;\n Options.TraceMalloc = Flags.trace_malloc;\n Options.RssLimitMb = Flags.rss_limit_mb;\n if (Flags.runs >= 0)\n Options.MaxNumberOfRuns = Flags.runs;\n if (!Inputs->empty() && !Flags.minimize_crash_internal_step)\n Options.OutputCorpus = (*Inputs)[0];\n Options.ReportSlowUnits = Flags.report_slow_units;\n if (Flags.artifact_prefix)\n Options.ArtifactPrefix = Flags.artifact_prefix;\n if (Flags.exact_artifact_path)\n Options.ExactArtifactPath = Flags.exact_artifact_path;\n std::vector Dictionary;\n if (Flags.dict)\n if (!ParseDictionaryFile(FileToString(Flags.dict), &Dictionary))\n return 1;\n if (Flags.verbosity > 0 && !Dictionary.empty())\n Printf(\"Dictionary: %zd entries\\n\", Dictionary.size());\n bool DoPlainRun = AllInputsAreFiles();\n Options.SaveArtifacts =\n !DoPlainRun || Flags.minimize_crash_internal_step;\n Options.PrintNewCovPcs = Flags.print_pcs;\n Options.PrintFinalStats = Flags.print_final_stats;\n Options.PrintCorpusStats = Flags.print_corpus_stats;\n Options.PrintCoverage = Flags.print_coverage;\n Options.DumpCoverage = Flags.dump_coverage;\n if (Flags.exit_on_src_pos)\n Options.ExitOnSrcPos = Flags.exit_on_src_pos;\n if (Flags.exit_on_item)\n Options.ExitOnItem = Flags.exit_on_item;\n\n unsigned Seed = Flags.seed;\n // Initialize Seed.\n if (Seed == 0)\n Seed = (std::chrono::system_clock::now().time_since_epoch().count() << 10) +\n GetPid();\n if (Flags.verbosity)\n Printf(\"INFO: Seed: %u\\n\", Seed);\n\n Random Rand(Seed);\n auto *MD = new MutationDispatcher(Rand, Options);\n auto *Corpus = new InputCorpus(Options.OutputCorpus);\n auto *F = new Fuzzer(Callback, *Corpus, *MD, Options);\n\n for (auto &U: Dictionary)\n if (U.size() <= Word::GetMaxSize())\n MD->AddWordToManualDictionary(Word(U.data(), U.size()));\n\n StartRssThread(F, Flags.rss_limit_mb);\n\n Options.HandleAbrt = Flags.handle_abrt;\n Options.HandleBus = Flags.handle_bus;\n Options.HandleFpe = Flags.handle_fpe;\n Options.HandleIll = Flags.handle_ill;\n Options.HandleInt = Flags.handle_int;\n Options.HandleSegv = Flags.handle_segv;\n Options.HandleTerm = Flags.handle_term;\n SetSignalHandler(Options);\n\n if (Flags.minimize_crash_internal_step)\n return MinimizeCrashInputInternalStep(F, Corpus);\n\n if (DoPlainRun) {\n Options.SaveArtifacts = false;\n int Runs = std::max(1, Flags.runs);\n Printf(\"%s: Running %zd inputs %d time(s) each.\\n\", ProgName->c_str(),\n Inputs->size(), Runs);\n for (auto &Path : *Inputs) {\n auto StartTime = system_clock::now();\n Printf(\"Running: %s\\n\", Path.c_str());\n for (int Iter = 0; Iter < Runs; Iter++)\n RunOneTest(F, Path.c_str(), Options.MaxLen);\n auto StopTime = system_clock::now();\n auto MS = duration_cast(StopTime - StartTime).count();\n Printf(\"Executed %s in %zd ms\\n\", Path.c_str(), (long)MS);\n }\n Printf(\"***\\n\"\n \"*** NOTE: fuzzing was not performed, you have only\\n\"\n \"*** executed the target code on a fixed set of inputs.\\n\"\n \"***\\n\");\n F->PrintFinalStats();\n exit(0);\n }\n\n if (Flags.merge) {\n if (Options.MaxLen == 0)\n F->SetMaxInputLen(kMaxSaneLen);\n if (TPC.UsingTracePcGuard()) {\n if (Flags.merge_control_file)\n F->CrashResistantMergeInternalStep(Flags.merge_control_file);\n else\n F->CrashResistantMerge(Args, *Inputs);\n } else {\n F->Merge(*Inputs);\n }\n exit(0);\n }\n\n size_t TemporaryMaxLen = Options.MaxLen ? Options.MaxLen : kMaxSaneLen;\n\n UnitVector InitialCorpus;\n for (auto &Inp : *Inputs) {\n Printf(\"Loading corpus dir: %s\\n\", Inp.c_str());\n ReadDirToVectorOfUnits(Inp.c_str(), &InitialCorpus, nullptr,\n TemporaryMaxLen, /*ExitOnError=*/false);\n }\n\n if (Options.MaxLen == 0) {\n size_t MaxLen = 0;\n for (auto &U : InitialCorpus)\n MaxLen = std::max(U.size(), MaxLen);\n F->SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxLen), kMaxSaneLen));\n }\n\n if (InitialCorpus.empty()) {\n InitialCorpus.push_back(Unit({'\\n'})); // Valid ASCII input.\n if (Options.Verbosity)\n Printf(\"INFO: A corpus is not provided, starting from an empty corpus\\n\");\n }\n F->ShuffleAndMinimize(&InitialCorpus);\n InitialCorpus.clear(); // Don't need this memory any more.\n F->Loop();\n\n if (Flags.verbosity)\n Printf(\"Done %d runs in %zd second(s)\\n\", F->getTotalNumberOfRuns(),\n F->secondsSinceProcessStartUp());\n F->PrintFinalStats();\n\n exit(0); // Don't let F destroy itself.\n}\n\n// Storage for global ExternalFunctions object.\nExternalFunctions *EF = nullptr;\n\n} // namespace fuzzer", "messages": null, "tools": null} {"id": "7e793125283efbf6", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "include/nlohmann/detail/iterators/iteration_proxy.hpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 8070, "sha256": "21c1359b471116234a37dedcff6b0f64c4fc160ac55817b8ded0f412b438ba8a", "text": "// __ _____ _____ _____\n// __| | __| | | | JSON for Modern C++\n// | | |__ | | | | | | version 3.12.0\n// |_____|_____|_____|_|___| https://github.com/nlohmann/json\n//\n// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann \n// SPDX-License-Identifier: MIT\n\n#pragma once\n\n#include // size_t\n#include // forward_iterator_tag\n#include // tuple_size, get, tuple_element\n#include // move\n\n#if JSON_HAS_RANGES\n #include // enable_borrowed_range\n#endif\n\n#include \n#include \n#include \n#include \n\nNLOHMANN_JSON_NAMESPACE_BEGIN\nnamespace detail\n{\n\ntemplate class iteration_proxy_value\n{\n public:\n using difference_type = std::ptrdiff_t;\n using value_type = iteration_proxy_value;\n using pointer = value_type *;\n using reference = value_type &;\n using iterator_category = std::forward_iterator_tag;\n using string_type = typename std::remove_cv< typename std::remove_reference().key() ) >::type >::type;\n\n private:\n /// the iterator\n IteratorType anchor{};\n /// an index for arrays (used to create key names)\n std::size_t array_index = 0;\n /// last stringified array index\n mutable std::size_t array_index_last = 0;\n /// a string representation of the array index\n mutable string_type array_index_str = \"0\";\n /// an empty string (to return a reference for primitive values)\n string_type empty_str{};\n\n public:\n explicit iteration_proxy_value() = default;\n explicit iteration_proxy_value(IteratorType it, std::size_t array_index_ = 0)\n noexcept(std::is_nothrow_move_constructible::value\n && std::is_nothrow_default_constructible::value)\n : anchor(std::move(it))\n , array_index(array_index_)\n {}\n\n iteration_proxy_value(iteration_proxy_value const&) = default;\n iteration_proxy_value& operator=(iteration_proxy_value const&) = default;\n // older GCCs are a bit fussy and require explicit noexcept specifiers on defaulted functions\n iteration_proxy_value(iteration_proxy_value&&)\n noexcept(std::is_nothrow_move_constructible::value\n && std::is_nothrow_move_constructible::value) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor,cppcoreguidelines-noexcept-move-operations)\n iteration_proxy_value& operator=(iteration_proxy_value&&)\n noexcept(std::is_nothrow_move_assignable::value\n && std::is_nothrow_move_assignable::value) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor,cppcoreguidelines-noexcept-move-operations)\n ~iteration_proxy_value() = default;\n\n /// dereference operator (needed for range-based for)\n const iteration_proxy_value& operator*() const\n {\n return *this;\n }\n\n /// increment operator (needed for range-based for)\n iteration_proxy_value& operator++()\n {\n ++anchor;\n ++array_index;\n\n return *this;\n }\n\n iteration_proxy_value operator++(int)& // NOLINT(cert-dcl21-cpp)\n {\n auto tmp = iteration_proxy_value(anchor, array_index);\n ++anchor;\n ++array_index;\n return tmp;\n }\n\n /// equality operator (needed for InputIterator)\n bool operator==(const iteration_proxy_value& o) const\n {\n return anchor == o.anchor;\n }\n\n /// inequality operator (needed for range-based for)\n bool operator!=(const iteration_proxy_value& o) const\n {\n return anchor != o.anchor;\n }\n\n /// return key of the iterator\n const string_type& key() const\n {\n JSON_ASSERT(anchor.m_object != nullptr);\n\n switch (anchor.m_object->type())\n {\n // use integer array index as key\n case value_t::array:\n {\n if (array_index != array_index_last)\n {\n int_to_string( array_index_str, array_index );\n array_index_last = array_index;\n }\n return array_index_str;\n }\n\n // use key from the object\n case value_t::object:\n return anchor.key();\n\n // use an empty key for all primitive types\n case value_t::null:\n case value_t::string:\n case value_t::boolean:\n case value_t::number_integer:\n case value_t::number_unsigned:\n case value_t::number_float:\n case value_t::binary:\n case value_t::discarded:\n default:\n return empty_str;\n }\n }\n\n /// return value of the iterator\n typename IteratorType::reference value() const\n {\n return anchor.value();\n }\n};\n\n/// proxy class for the items() function\ntemplate class iteration_proxy\n{\n private:\n /// the container to iterate\n typename IteratorType::pointer container = nullptr;\n\n public:\n explicit iteration_proxy() = default;\n\n /// construct iteration proxy from a container\n explicit iteration_proxy(typename IteratorType::reference cont) noexcept\n : container(&cont) {}\n\n iteration_proxy(iteration_proxy const&) = default;\n iteration_proxy& operator=(iteration_proxy const&) = default;\n iteration_proxy(iteration_proxy&&) noexcept = default;\n iteration_proxy& operator=(iteration_proxy&&) noexcept = default;\n ~iteration_proxy() = default;\n\n /// return iterator begin (needed for range-based for)\n iteration_proxy_value begin() const noexcept\n {\n return iteration_proxy_value(container->begin());\n }\n\n /// return iterator end (needed for range-based for)\n iteration_proxy_value end() const noexcept\n {\n return iteration_proxy_value(container->end());\n }\n};\n\n// Structured Bindings Support\n// For further reference see https://blog.tartanllama.xyz/structured-bindings/\n// And see https://github.com/nlohmann/json/pull/1391\ntemplate = 0>\nauto get(const nlohmann::detail::iteration_proxy_value& i) -> decltype(i.key())\n{\n return i.key();\n}\n// Structured Bindings Support\n// For further reference see https://blog.tartanllama.xyz/structured-bindings/\n// And see https://github.com/nlohmann/json/pull/1391\ntemplate = 0>\nauto get(const nlohmann::detail::iteration_proxy_value& i) -> decltype(i.value())\n{\n return i.value();\n}\n\n} // namespace detail\nNLOHMANN_JSON_NAMESPACE_END\n\n// The Addition to the STD Namespace is required to add\n// Structured Bindings Support to the iteration_proxy_value class\n// For further reference see https://blog.tartanllama.xyz/structured-bindings/\n// And see https://github.com/nlohmann/json/pull/1391\nnamespace std\n{\n\n#if defined(__clang__)\n // Fix: https://github.com/nlohmann/json/issues/1401\n #pragma clang diagnostic push\n #pragma clang diagnostic ignored \"-Wmismatched-tags\"\n#endif\ntemplate\nclass tuple_size<::nlohmann::detail::iteration_proxy_value> // NOLINT(cert-dcl58-cpp)\n : public std::integral_constant {};\n\ntemplate\nclass tuple_element> // NOLINT(cert-dcl58-cpp)\n{\n public:\n using type = decltype(\n get(std::declval <\n ::nlohmann::detail::iteration_proxy_value> ()));\n};\n#if defined(__clang__)\n #pragma clang diagnostic pop\n#endif\n\n} // namespace std\n\n#if JSON_HAS_RANGES\n template \n inline constexpr bool ::std::ranges::enable_borrowed_range<::nlohmann::detail::iteration_proxy> = true;\n#endif", "messages": null, "tools": null} {"id": "7ec2108007fb1436", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/basic_json__basic_json.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 337, "sha256": "916e9ec38b4f4ee166e1b478add09174b3486f1f70a34d335f58d4b220638c4e", "text": "#include \n#include \n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON array\n json j1 = {\"one\", \"two\", 3, 4.5, false};\n\n // create a copy\n json j2(j1);\n\n // serialize the JSON array\n std::cout << j1 << \" = \" << j2 << '\\n';\n std::cout << std::boolalpha << (j1 == j2) << '\\n';\n}", "messages": null, "tools": null} {"id": "7ed513a56c12c295", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/thirdparty/Fuzzer/FuzzerCrossOver.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 1869, "sha256": "be61d99e8f36bccc166bd76063d9d52604a0598d7c1ddeda554fc2eb49d1c67c", "text": "//===- FuzzerCrossOver.cpp - Cross over two test inputs -------------------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n// Cross over test inputs.\n//===----------------------------------------------------------------------===//\n\n#include \"FuzzerDefs.h\"\n#include \"FuzzerMutate.h\"\n#include \"FuzzerRandom.h\"\n#include \n\nnamespace fuzzer {\n\n// Cross Data1 and Data2, store the result (up to MaxOutSize bytes) in Out.\nsize_t MutationDispatcher::CrossOver(const uint8_t *Data1, size_t Size1,\n const uint8_t *Data2, size_t Size2,\n uint8_t *Out, size_t MaxOutSize) {\n assert(Size1 || Size2);\n MaxOutSize = Rand(MaxOutSize) + 1;\n size_t OutPos = 0;\n size_t Pos1 = 0;\n size_t Pos2 = 0;\n size_t *InPos = &Pos1;\n size_t InSize = Size1;\n const uint8_t *Data = Data1;\n bool CurrentlyUsingFirstData = true;\n while (OutPos < MaxOutSize && (Pos1 < Size1 || Pos2 < Size2)) {\n // Merge a part of Data into Out.\n size_t OutSizeLeft = MaxOutSize - OutPos;\n if (*InPos < InSize) {\n size_t InSizeLeft = InSize - *InPos;\n size_t MaxExtraSize = std::min(OutSizeLeft, InSizeLeft);\n size_t ExtraSize = Rand(MaxExtraSize) + 1;\n memcpy(Out + OutPos, Data + *InPos, ExtraSize);\n OutPos += ExtraSize;\n (*InPos) += ExtraSize;\n }\n // Use the other input data on the next iteration.\n InPos = CurrentlyUsingFirstData ? &Pos2 : &Pos1;\n InSize = CurrentlyUsingFirstData ? Size2 : Size1;\n Data = CurrentlyUsingFirstData ? Data2 : Data1;\n CurrentlyUsingFirstData = !CurrentlyUsingFirstData;\n }\n return OutPos;\n}\n\n} // namespace fuzzer", "messages": null, "tools": null} {"id": "7f25896e2717317f", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/operator__value_t.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 1360, "sha256": "2a9a99b07a10974bb7262236ee861374dc360b477df3c100c7e9a0345a4f4e77", "text": "#include \n#include \n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = -17;\n json j_number_unsigned = 42u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n\n // call operator value_t()\n json::value_t t_null = j_null;\n json::value_t t_boolean = j_boolean;\n json::value_t t_number_integer = j_number_integer;\n json::value_t t_number_unsigned = j_number_unsigned;\n json::value_t t_number_float = j_number_float;\n json::value_t t_object = j_object;\n json::value_t t_array = j_array;\n json::value_t t_string = j_string;\n\n // print types\n std::cout << std::boolalpha;\n std::cout << (t_null == json::value_t::null) << '\\n';\n std::cout << (t_boolean == json::value_t::boolean) << '\\n';\n std::cout << (t_number_integer == json::value_t::number_integer) << '\\n';\n std::cout << (t_number_unsigned == json::value_t::number_unsigned) << '\\n';\n std::cout << (t_number_float == json::value_t::number_float) << '\\n';\n std::cout << (t_object == json::value_t::object) << '\\n';\n std::cout << (t_array == json::value_t::array) << '\\n';\n std::cout << (t_string == json::value_t::string) << '\\n';\n}", "messages": null, "tools": null} {"id": "7fb05dc0af04338b", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/thirdparty/Fuzzer/FuzzerMain.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 714, "sha256": "4221ced17beb1d98341bca52c76d37cf08c03e10a8c1cef9d885968ed3fec86a", "text": "//===- FuzzerMain.cpp - main() function and flags -------------------------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n// main() and flags.\n//===----------------------------------------------------------------------===//\n\n#include \"FuzzerDefs.h\"\n\nextern \"C\" {\n// This function should be defined by the user.\nint LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size);\n} // extern \"C\"\n\nint main(int argc, char **argv) {\n return fuzzer::FuzzerDriver(&argc, &argv, LLVMFuzzerTestOneInput);\n}", "messages": null, "tools": null} {"id": "800f2db03cc4a101", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/push_back.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 439, "sha256": "df6fb649176d706bfe98f8839fa34ca117068a2ab188b37af360b37df73f05f4", "text": "#include \n#include \n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json array = {1, 2, 3, 4, 5};\n json null;\n\n // print values\n std::cout << array << '\\n';\n std::cout << null << '\\n';\n\n // add values\n array.push_back(6);\n array += 7;\n null += \"first\";\n null += \"second\";\n\n // print values\n std::cout << array << '\\n';\n std::cout << null << '\\n';\n}", "messages": null, "tools": null} {"id": "80ff55860278462c", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/thirdparty/Fuzzer/test/FourIndependentBranchesTest.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 612, "sha256": "93a37948933c9979b4c84f2624273973e7ef9648e0644f662468c43645452a45", "text": "// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n\n// Simple test for a fuzzer. The fuzzer must find the string \"FUZZ\".\n#include \n#include \n#include \n#include \n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {\n int bits = 0;\n if (Size > 0 && Data[0] == 'F') bits |= 1;\n if (Size > 1 && Data[1] == 'U') bits |= 2;\n if (Size > 2 && Data[2] == 'Z') bits |= 4;\n if (Size > 3 && Data[3] == 'Z') bits |= 8;\n if (bits == 15) {\n std::cerr << \"BINGO!\\n\";\n exit(1);\n }\n return 0;\n}", "messages": null, "tools": null} {"id": "81faa92344346121", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/worker/worker/main-format-es.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 1283, "sha256": "c7ac9d6db27a985a06df03c99fd78c811fc1b6c9663188bfad062ef27845e751", "text": "// run when format es\nimport NestedWorker from '../emit-chunk-nested-worker?worker'\nimport ImportMetaGlobWorker from '../importMetaGlob.worker?worker'\n\nfunction text(el, text) {\n document.querySelector(el).textContent = text\n}\n\ntext('.format-es', 'format es:')\n\nconst nestedWorker = new NestedWorker()\nconst dataList = []\nnestedWorker.addEventListener('message', (ev) => {\n dataList.push(ev.data)\n text(\n '.emit-chunk-worker',\n JSON.stringify(\n dataList.sort(\n (a, b) => JSON.stringify(a).length - JSON.stringify(b).length,\n ),\n ),\n )\n})\n\nconst dynamicImportWorker = new Worker(\n new URL('../emit-chunk-dynamic-import-worker.js', import.meta.url),\n {\n type: 'module',\n },\n)\ndynamicImportWorker.addEventListener('message', (ev) => {\n text('.emit-chunk-dynamic-import-worker', JSON.stringify(ev.data))\n})\n\nconst moduleWorker = new Worker(\n new URL('../module-and-worker.js', import.meta.url),\n { type: 'module' },\n)\n\nmoduleWorker.addEventListener('message', (ev) => {\n text('.module-and-worker-worker', JSON.stringify(ev.data))\n})\n\nconst importMetaGlobWorker = new ImportMetaGlobWorker()\n\nimportMetaGlobWorker.postMessage('1')\n\nimportMetaGlobWorker.addEventListener('message', (e) => {\n text('.importMetaGlob-worker', JSON.stringify(e.data))\n})", "messages": null, "tools": null} {"id": "82722a318d5c062a", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/thirdparty/Fuzzer/FuzzerTracePC.h", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 4731, "sha256": "ab3619221a77cd45e2913142b952fc9281ad9a203b746da7732d255defbc762d", "text": "//===- FuzzerTracePC.h - Internal header for the Fuzzer ---------*- C++ -* ===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n// fuzzer::TracePC\n//===----------------------------------------------------------------------===//\n\n#ifndef LLVM_FUZZER_TRACE_PC\n#define LLVM_FUZZER_TRACE_PC\n\n#include \"FuzzerDefs.h\"\n#include \"FuzzerValueBitMap.h\"\n#include \n\nnamespace fuzzer {\n\n// TableOfRecentCompares (TORC) remembers the most recently performed\n// comparisons of type T.\n// We record the arguments of CMP instructions in this table unconditionally\n// because it seems cheaper this way than to compute some expensive\n// conditions inside __sanitizer_cov_trace_cmp*.\n// After the unit has been executed we may decide to use the contents of\n// this table to populate a Dictionary.\ntemplate\nstruct TableOfRecentCompares {\n static const size_t kSize = kSizeT;\n struct Pair {\n T A, B;\n };\n void Insert(size_t Idx, T Arg1, T Arg2) {\n Idx = Idx % kSize;\n Table[Idx].A = Arg1;\n Table[Idx].B = Arg2;\n }\n\n Pair Get(size_t I) { return Table[I % kSize]; }\n\n Pair Table[kSize];\n};\n\nclass TracePC {\n public:\n static const size_t kFeatureSetSize = ValueBitMap::kNumberOfItems;\n\n void HandleTrace(uint32_t *guard, uintptr_t PC);\n void HandleInit(uint32_t *start, uint32_t *stop);\n void HandleCallerCallee(uintptr_t Caller, uintptr_t Callee);\n void HandleValueProfile(size_t Value) { ValueProfileMap.AddValue(Value); }\n template void HandleCmp(void *PC, T Arg1, T Arg2);\n size_t GetTotalPCCoverage();\n void SetUseCounters(bool UC) { UseCounters = UC; }\n void SetUseValueProfile(bool VP) { UseValueProfile = VP; }\n void SetPrintNewPCs(bool P) { DoPrintNewPCs = P; }\n template size_t CollectFeatures(Callback CB);\n bool UpdateValueProfileMap(ValueBitMap *MaxValueProfileMap) {\n return UseValueProfile && MaxValueProfileMap->MergeFrom(ValueProfileMap);\n }\n\n void ResetMaps() {\n ValueProfileMap.Reset();\n memset(Counters, 0, sizeof(Counters));\n }\n\n void UpdateFeatureSet(size_t CurrentElementIdx, size_t CurrentElementSize);\n void PrintFeatureSet();\n\n void PrintModuleInfo();\n\n void PrintCoverage();\n void DumpCoverage();\n\n void AddValueForMemcmp(void *caller_pc, const void *s1, const void *s2,\n size_t n);\n void AddValueForStrcmp(void *caller_pc, const char *s1, const char *s2,\n size_t n);\n\n bool UsingTracePcGuard() const {return NumModules; }\n\n static const size_t kTORCSize = 1 << 5;\n TableOfRecentCompares TORC4;\n TableOfRecentCompares TORC8;\n\n void PrintNewPCs();\n size_t GetNumPCs() const { return Min(kNumPCs, NumGuards + 1); }\n uintptr_t GetPC(size_t Idx) {\n assert(Idx < GetNumPCs());\n return PCs[Idx];\n }\n\nprivate:\n bool UseCounters = false;\n bool UseValueProfile = false;\n bool DoPrintNewPCs = false;\n\n struct Module {\n uint32_t *Start, *Stop;\n };\n\n Module Modules[4096];\n size_t NumModules; // linker-initialized.\n size_t NumGuards; // linker-initialized.\n\n static const size_t kNumCounters = 1 << 14;\n alignas(8) uint8_t Counters[kNumCounters];\n\n static const size_t kNumPCs = 1 << 24;\n uintptr_t PCs[kNumPCs];\n\n std::set *PrintedPCs;\n\n ValueBitMap ValueProfileMap;\n};\n\ntemplate \nsize_t TracePC::CollectFeatures(Callback CB) {\n if (!UsingTracePcGuard()) return 0;\n size_t Res = 0;\n const size_t Step = 8;\n assert(reinterpret_cast(Counters) % Step == 0);\n size_t N = Min(kNumCounters, NumGuards + 1);\n N = (N + Step - 1) & ~(Step - 1); // Round up.\n for (size_t Idx = 0; Idx < N; Idx += Step) {\n uint64_t Bundle = *reinterpret_cast(&Counters[Idx]);\n if (!Bundle) continue;\n for (size_t i = Idx; i < Idx + Step; i++) {\n uint8_t Counter = (Bundle >> ((i - Idx) * 8)) & 0xff;\n if (!Counter) continue;\n Counters[i] = 0;\n unsigned Bit = 0;\n /**/ if (Counter >= 128) Bit = 7;\n else if (Counter >= 32) Bit = 6;\n else if (Counter >= 16) Bit = 5;\n else if (Counter >= 8) Bit = 4;\n else if (Counter >= 4) Bit = 3;\n else if (Counter >= 3) Bit = 2;\n else if (Counter >= 2) Bit = 1;\n size_t Feature = (i * 8 + Bit);\n if (CB(Feature))\n Res++;\n }\n }\n if (UseValueProfile)\n ValueProfileMap.ForEach([&](size_t Idx) {\n if (CB(NumGuards * 8 + Idx))\n Res++;\n });\n return Res;\n}\n\nextern TracePC TPC;\n\n} // namespace fuzzer\n\n#endif // LLVM_FUZZER_TRACE_PC", "messages": null, "tools": null} {"id": "82f7a005456643fa", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/assets/__tests__/relative-base/assets-relative-base.spec.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 7499, "sha256": "d98379fe98dcdc93588e24c7d49cfb5d32559e65eacebac44a281867706d1950", "text": "import { beforeAll, describe, expect, test } from 'vitest'\nimport {\n browserLogs,\n findAssetFile,\n getBg,\n getColor,\n isBuild,\n isBundled,\n isBundledDev,\n page,\n} from '~utils'\n\n// bundled dev serves hashed asset URLs like build. But it writes them to the\n// default `assets/` folder, because build's custom assetFileNames setting\n// (other-assets/) is not applied here.\nconst absoluteAssetMatch = isBuild\n ? /http.*\\/other-assets\\/asset-[-\\w]{8}\\.png/\n : isBundledDev\n ? /\\/assets\\/asset-[-\\w]{8}\\.png/\n : '/nested/asset.png'\n\n// Asset URLs in CSS are relative to the same dir, the computed\n// style returns the absolute URL in the test\nconst cssBgAssetMatch = absoluteAssetMatch\n\nconst iconMatch = `/icon.png`\n\nconst absoluteIconMatch = isBundled\n ? /http.*\\/icon-[-\\w]{8}\\.png/\n : '/nested/icon.png'\n\nconst absolutePublicIconMatch = isBuild ? /http.*\\/icon\\.png/ : '/icon.png'\n\ntest('should have no 404s', () => {\n browserLogs.forEach((msg) => {\n expect(msg).not.toMatch('404')\n })\n})\n\ndescribe('raw references from /public', () => {\n test('load raw js from /public', async () => {\n expect(await page.textContent('.raw-js')).toMatch('[success]')\n })\n\n test('load raw css from /public', async () => {\n expect(await getColor('.raw-css')).toBe('red')\n })\n})\n\ntest('import-expression from simple script', async () => {\n expect(await page.textContent('.import-expression')).toMatch(\n '[success][success]',\n )\n})\n\ndescribe('asset imports from js', () => {\n test('relative', async () => {\n expect(await page.textContent('.asset-import-relative')).toMatch(\n cssBgAssetMatch,\n )\n })\n\n test('absolute', async () => {\n expect(await page.textContent('.asset-import-absolute')).toMatch(\n cssBgAssetMatch,\n )\n })\n\n test('from /public', async () => {\n expect(await page.textContent('.public-import')).toMatch(\n absolutePublicIconMatch,\n )\n })\n})\n\ndescribe('css url() references', () => {\n test('fonts', async () => {\n expect(\n await page.evaluate(() => {\n return (document as any).fonts.check('700 32px Inter')\n }),\n ).toBe(true)\n })\n\n test('relative', async () => {\n const bg = await getBg('.css-url-relative')\n expect(bg).toMatch(cssBgAssetMatch)\n })\n\n test('image-set relative', async () => {\n const imageSet = await getBg('.css-image-set-relative')\n imageSet.split(', ').forEach((s) => {\n expect(s).toMatch(cssBgAssetMatch)\n })\n })\n\n test('image-set without the url() call', async () => {\n const imageSet = await getBg('.css-image-set-without-url-call')\n imageSet.split(', ').forEach((s) => {\n expect(s).toMatch(cssBgAssetMatch)\n })\n })\n\n test('image-set with var', async () => {\n const imageSet = await getBg('.css-image-set-with-var')\n imageSet.split(', ').forEach((s) => {\n expect(s).toMatch(cssBgAssetMatch)\n })\n })\n\n test('image-set with mix', async () => {\n const imageSet = await getBg('.css-image-set-mix-url-var')\n imageSet.split(', ').forEach((s) => {\n expect(s).toMatch(cssBgAssetMatch)\n })\n })\n\n test('relative in @import', async () => {\n expect(await getBg('.css-url-relative-at-imported')).toMatch(\n cssBgAssetMatch,\n )\n })\n\n test('absolute', async () => {\n expect(await getBg('.css-url-absolute')).toMatch(cssBgAssetMatch)\n })\n\n test('from /public', async () => {\n expect(await getBg('.css-url-public')).toMatch(iconMatch)\n })\n\n test('multiple urls on the same line', async () => {\n const bg = await getBg('.css-url-same-line')\n expect(bg).toMatch(cssBgAssetMatch)\n expect(bg).toMatch(iconMatch)\n })\n\n test('aliased', async () => {\n const bg = await getBg('.css-url-aliased')\n expect(bg).toMatch(cssBgAssetMatch)\n })\n\n test('nested manual chunks', async () => {\n const bg = await getBg('.css-manual-chunks-relative')\n expect(bg).toMatch(cssBgAssetMatch)\n })\n})\n\ndescribe.runIf(isBuild)('index.css URLs', () => {\n let css: string\n beforeAll(() => {\n css = findAssetFile(/index.*\\.css$/, 'relative-base', 'other-assets')\n })\n\n test('relative asset URL', () => {\n expect(css).toMatch(`./asset-`)\n })\n\n test('preserve postfix query/hash', () => {\n expect(css).toMatch(`woff2?#iefix`)\n })\n})\n\ndescribe('image', () => {\n test('srcset', async () => {\n const img = await page.$('.img-src-set')\n const srcset = await img.getAttribute('srcset')\n srcset.split(', ').forEach((s) => {\n expect(s).toMatch(\n isBuild\n ? /other-assets\\/asset-[-\\w]{8}\\.png \\dx/\n : isBundledDev\n ? /\\/assets\\/asset-[-\\w]{8}\\.png \\dx/\n : /\\.\\/nested\\/asset\\.png \\dx/,\n )\n })\n })\n})\n\ndescribe('svg fragments', () => {\n // 404 is checked already, so here we just ensure the urls end with #fragment\n // bundled dev drops the #fragment postfix from hashed asset URLs (vitejs/vite#23028)\n test.skipIf(isBundledDev)('img url', async () => {\n const img = await page.$('.svg-frag-img')\n expect(await img.getAttribute('src')).toMatch(/svg#icon-clock-view$/)\n })\n\n // bundled dev: #fragment dropped (see 'img url')\n test.skipIf(isBundledDev)('via css url()', async () => {\n expect(await getBg('.icon')).toMatch(/svg#icon-clock-view\"\\)$/)\n })\n\n test('from js import', async () => {\n const img = await page.$('.svg-frag-import')\n expect(await img.getAttribute('src')).toMatch(/svg#icon-heart-view$/)\n })\n})\n\ntest('?raw import', async () => {\n expect(await page.textContent('.raw')).toMatch('SVG')\n})\n\ntest('?url import', async () => {\n expect(await page.textContent('.url')).toMatch(\n isBuild\n ? /http.*\\/other-assets\\/foo-[-\\w]{8}\\.js/\n : isBundledDev\n ? /\\/assets\\/foo-[-\\w]{8}\\.js/\n : `/foo.js`,\n )\n})\n\ntest('?url import on css', async () => {\n const txt = await page.textContent('.url-css')\n expect(txt).toMatch(\n isBuild\n ? /http.*\\/other-assets\\/icons-[-\\w]{8}\\.css/\n : isBundledDev\n ? /\\/assets\\/icons-[-\\w]{8}\\.css/\n : '/css/icons.css',\n )\n isBuild &&\n expect(findAssetFile(/index.*\\.js$/, 'relative-base', 'entries')).toMatch(\n /icons-.+\\.css(?!\\?used)/,\n )\n})\n\ntest('new URL(..., import.meta.url)', async () => {\n const absoluteImgMatch = isBuild\n ? /http.*\\/other-assets\\/img-[-\\w]{8}\\.png/\n : isBundledDev\n ? /\\/assets\\/img-[-\\w]{8}\\.png/\n : '/import-meta-url/img.png'\n expect(await page.textContent('.import-meta-url')).toMatch(absoluteImgMatch)\n})\n\ntest('new URL(`${dynamic}`, import.meta.url)', async () => {\n const dynamic1 = await page.textContent('.dynamic-import-meta-url-1')\n expect(dynamic1).toMatch(absoluteIconMatch)\n const dynamic2 = await page.textContent('.dynamic-import-meta-url-2')\n expect(dynamic2).toMatch(absoluteAssetMatch)\n})\n\ntest('new URL(`non-existent`, import.meta.url)', async () => {\n expect(await page.textContent('.non-existent-import-meta-url')).toMatch(\n '/non-existent',\n )\n})\n\ntest('inline style test', async () => {\n expect(await getBg('.inline-style')).toMatch(cssBgAssetMatch)\n expect(await getBg('.style-url-assets')).toMatch(cssBgAssetMatch)\n})\n\ntest('html import word boundary', async () => {\n expect(await page.textContent('.obj-import-express')).toMatch(\n 'ignore object import prop',\n )\n expect(await page.textContent('.string-import-express')).toMatch('no load')\n})\n\ntest('relative path in html asset', async () => {\n expect(await page.textContent('.relative-js')).toMatch('hello')\n expect(await getColor('.relative-css')).toMatch('red')\n})", "messages": null, "tools": null} {"id": "82feadc548f05ef6", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/swap__object_t.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 493, "sha256": "9408af2d97151663b5830e864e79ba9487ec0a5dbded861645ec56a71ebd327f", "text": "#include \n#include \n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value\n json value = { {\"translation\", {{\"one\", \"eins\"}, {\"two\", \"zwei\"}}} };\n\n // create an object_t\n json::object_t object = {{\"cow\", \"Kuh\"}, {\"dog\", \"Hund\"}};\n\n // swap the object stored in the JSON value\n value[\"translation\"].swap(object);\n\n // output the values\n std::cout << \"value = \" << value << '\\n';\n std::cout << \"object = \" << object << '\\n';\n}", "messages": null, "tools": null} {"id": "83059f796f84f624", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/ssr-deps/module-condition/module.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 251, "sha256": "e241c1338b1b7e8a91104065f2d86aecea1d8a2d79a9f72b096ce464a02fec5a", "text": "// this is written in ESM but the file extension implies this is evaluated as CJS.\n// BUT this doesn't matter in practice as the `module` condition is not used in node.\n// hence SSR should not load this file.\nexport default '[fail] should not load me'", "messages": null, "tools": null} {"id": "830f512a5b7d790d", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/ssr-html/__tests__/ssr-html.spec.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 4850, "sha256": "754a6f34b02e92b69edd50c6ad616349ee0542ccaff2952da2aeb264b7a7d844", "text": "import { execFile } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { setTimeout } from 'node:timers/promises'\nimport { describe, expect, test } from 'vitest'\nimport { port, serverLogs } from './serve'\nimport { editFile, isServe, page } from '~utils'\n\nconst url = `http://localhost:${port}`\n\ndescribe.runIf(isServe)('injected inline scripts', () => {\n test('no injected inline scripts are present', async () => {\n await page.goto(url)\n const inlineScripts = await page.$$eval('script', (nodes) =>\n nodes.filter((n) => !n.getAttribute('src') && n.innerHTML),\n )\n expect(inlineScripts).toHaveLength(0)\n })\n\n test('injected script proxied correctly', async () => {\n await page.goto(url)\n const proxiedScripts = await page.$$eval('script', (nodes) =>\n nodes\n .filter((n) => {\n const src = n.getAttribute('src')\n if (!src) return false\n return src.includes('?html-proxy&index')\n })\n .map((n) => n.getAttribute('src')),\n )\n\n // assert at least 1 proxied script exists\n expect(proxiedScripts).not.toHaveLength(0)\n\n const scriptContents = await Promise.all(\n proxiedScripts.map((src) => fetch(url + src).then((res) => res.text())),\n )\n\n // all proxied scripts return code\n for (const code of scriptContents) {\n expect(code).toBeTruthy()\n }\n })\n})\n\ndescribe.runIf(isServe)('trailing slash html paths', () => {\n test('pre-transforms relative module scripts from the trailing slash directory', async () => {\n serverLogs.length = 0\n\n const response = await fetch(`${url}/trailing-slash/dir/`)\n expect(response.status).toBe(200)\n await response.text()\n\n await setTimeout(100) // wait for pre-transform to happen\n expect(serverLogs).not.toEqual(\n expect.arrayContaining([expect.stringContaining('Pre-transform error')]),\n )\n })\n\n test('loads relative module scripts from the trailing slash directory', async () => {\n await page.goto(`${url}/trailing-slash/dir/`)\n\n await expect\n .poll(() => page.textContent('.relative-script'))\n .toBe('relative module loaded')\n await expect\n .poll(() => page.textContent('.relative-parent-script'))\n .toBe('relative parent module loaded')\n })\n})\n\ndescribe.runIf(isServe)('hmr', () => {\n test('handle virtual module updates', async () => {\n await page.goto(url)\n const el = await page.$('.virtual')\n expect(await el.textContent()).toBe('[success]')\n\n const loadPromise = page.waitForEvent('load')\n editFile('src/importedVirtual.js', (code) =>\n code.replace('[success]', '[wow]'),\n )\n await loadPromise\n\n await expect\n .poll(async () => {\n const el = await page.$('.virtual')\n return await el.textContent()\n })\n .toMatch('[wow]')\n })\n})\n\nconst execFileAsync = promisify(execFile)\n\ndescribe.runIf(isServe)('stacktrace', () => {\n for (const ext of ['js', 'ts']) {\n for (const sourcemapsEnabled of [false, true]) {\n test(`stacktrace of ${ext} is correct when sourcemaps is${\n sourcemapsEnabled ? '' : ' not'\n } enabled in Node.js`, async () => {\n const testStacktraceFile = path.resolve(\n import.meta.dirname,\n '../test-stacktrace.js',\n )\n\n const p = await execFileAsync('node', [\n testStacktraceFile,\n '' + sourcemapsEnabled,\n ext,\n ])\n const lines = p.stdout\n .split('\\n')\n .filter((line) => line.includes('Module.error'))\n\n const reg = new RegExp(\n path\n .resolve(import.meta.dirname, '../src', `error-${ext}.${ext}`)\n .replace(/\\\\/g, '\\\\\\\\') + ':2:9',\n 'i',\n )\n\n lines.forEach((line) => {\n expect(line.trim()).toMatch(reg)\n })\n })\n }\n }\n\n test('with Vite runtime', async () => {\n await execFileAsync('node', ['test-stacktrace-runtime.js'], {\n cwd: fileURLToPath(new URL('..', import.meta.url)),\n })\n })\n})\n\n// --experimental-network-imports is going to be dropped\n// https://github.com/nodejs/node/pull/53822\nconst noNetworkImports = Number(process.version.match(/^v(\\d+)\\./)[1]) >= 22\n\ndescribe.runIf(isServe && !noNetworkImports)('network-imports', () => {\n test('with Vite SSR', async () => {\n await execFileAsync(\n 'node',\n ['--experimental-network-imports', 'test-network-imports.js'],\n {\n cwd: fileURLToPath(new URL('..', import.meta.url)),\n },\n )\n })\n\n test('with Vite runtime', async () => {\n await execFileAsync(\n 'node',\n [\n '--experimental-network-imports',\n 'test-network-imports.js',\n '--module-runner',\n ],\n {\n cwd: fileURLToPath(new URL('..', import.meta.url)),\n },\n )\n })\n})", "messages": null, "tools": null} {"id": "834b7c13200ac546", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/tsconfig-json/src/main.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 505, "sha256": "0e8a238e2328c30d3acc66108ac03b77ce1a01fc6cc13e1fccef421f473fea86", "text": "// @ts-nocheck\nimport '../nested/main'\nimport '../nested-with-extends/main'\nimport './decorator'\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-imports\nimport { MainTypeOnlyClass } from './not-used-type'\n\nclass MainBase {\n set data(value: string) {\n console.log('data setter in MainBase')\n }\n}\nclass MainDerived extends MainBase {\n // No longer triggers a 'console.log'\n // when using 'useDefineForClassFields'.\n data = 10\n\n foo?: MainTypeOnlyClass\n}\n\nconst d = new MainDerived()", "messages": null, "tools": null} {"id": "839a05c5decd897c", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/api/json_sax/number_integer.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 512, "sha256": "f4405f1de84a3b3138b0bcfd6ea3ce3699ad13e2cec7a643c7bd3b455a0279da", "text": "# nlohmann::json_sax::number_integer\n\n```cpp\nvirtual bool number_integer(number_integer_t val) = 0;\n```\n\nAn integer number was read.\n\n## Parameters\n\n`val` (in)\n: integer value\n\n## Return value\n\nWhether parsing should proceed.\n\n## Examples\n\n??? example\n\n The example below shows how the SAX interface is used.\n\n ```cpp\n --8<-- \"examples/sax_parse.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/sax_parse.output\"\n ```\n\n## Version history\n\n- Added in version 3.2.0.", "messages": null, "tools": null} {"id": "83eaf8b7ab7646f8", "category": "code", "domain": "code", "source": "flask", "license": "BSD-3-Clause", "license_url": "https://spdx.org/licenses/BSD-3-Clause.html", "path": "tests/test_session_interface.py", "lang": "python", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/pallets/flask", "commit": "6a2f545bfd8ed31e19066a299296917e034aca58", "collector": "tools/harvest.py"}, "chars": 783, "sha256": "e31da09361f8fc3a90f51b881bc9f24c119b92c3ea27f1f46c601061891dce8b", "text": "import flask\nfrom flask.globals import app_ctx\nfrom flask.sessions import SessionInterface\n\n\ndef test_open_session_with_endpoint():\n \"\"\"If request.endpoint (or other URL matching behavior) is needed\n while loading the session, RequestContext.match_request() can be\n called manually.\n \"\"\"\n\n class MySessionInterface(SessionInterface):\n def save_session(self, app, session, response):\n pass\n\n def open_session(self, app, request):\n app_ctx.match_request()\n assert request.endpoint is not None\n\n app = flask.Flask(__name__)\n app.session_interface = MySessionInterface()\n\n @app.get(\"/\")\n def index():\n return \"Hello, World!\"\n\n response = app.test_client().get(\"/\")\n assert response.status_code == 200", "messages": null, "tools": null} {"id": "8489747c148b245a", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/thirdparty/Fuzzer/FuzzerUtilDarwin.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 5599, "sha256": "f3394663938738753bc636ff1c21bbfdf010ad2acb7778752143d81b95024b3f", "text": "//===- FuzzerUtilDarwin.cpp - Misc utils ----------------------------------===//\n//\n// The LLVM Compiler Infrastructure\n//\n// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n// Misc utils for Darwin.\n//===----------------------------------------------------------------------===//\n#include \"FuzzerDefs.h\"\n#if LIBFUZZER_APPLE\n\n#include \"FuzzerIO.h\"\n#include \n#include \n#include \n#include \n\n// There is no header for this on macOS so declare here\nextern \"C\" char **environ;\n\nnamespace fuzzer {\n\nstatic std::mutex SignalMutex;\n// Global variables used to keep track of how signal handling should be\n// restored. They should **not** be accessed without holding `SignalMutex`.\nstatic int ActiveThreadCount = 0;\nstatic struct sigaction OldSigIntAction;\nstatic struct sigaction OldSigQuitAction;\nstatic sigset_t OldBlockedSignalsSet;\n\n// This is a reimplementation of Libc's `system()`. On Darwin the Libc\n// implementation contains a mutex which prevents it from being used\n// concurrently. This implementation **can** be used concurrently. It sets the\n// signal handlers when the first thread enters and restores them when the last\n// thread finishes execution of the function and ensures this is not racey by\n// using a mutex.\nint ExecuteCommand(const std::string &Command) {\n posix_spawnattr_t SpawnAttributes;\n if (posix_spawnattr_init(&SpawnAttributes))\n return -1;\n // Block and ignore signals of the current process when the first thread\n // enters.\n {\n std::lock_guard Lock(SignalMutex);\n if (ActiveThreadCount == 0) {\n static struct sigaction IgnoreSignalAction;\n sigset_t BlockedSignalsSet;\n memset(&IgnoreSignalAction, 0, sizeof(IgnoreSignalAction));\n IgnoreSignalAction.sa_handler = SIG_IGN;\n\n if (sigaction(SIGINT, &IgnoreSignalAction, &OldSigIntAction) == -1) {\n Printf(\"Failed to ignore SIGINT\\n\");\n (void)posix_spawnattr_destroy(&SpawnAttributes);\n return -1;\n }\n if (sigaction(SIGQUIT, &IgnoreSignalAction, &OldSigQuitAction) == -1) {\n Printf(\"Failed to ignore SIGQUIT\\n\");\n // Try our best to restore the signal handlers.\n (void)sigaction(SIGINT, &OldSigIntAction, NULL);\n (void)posix_spawnattr_destroy(&SpawnAttributes);\n return -1;\n }\n\n (void)sigemptyset(&BlockedSignalsSet);\n (void)sigaddset(&BlockedSignalsSet, SIGCHLD);\n if (sigprocmask(SIG_BLOCK, &BlockedSignalsSet, &OldBlockedSignalsSet) ==\n -1) {\n Printf(\"Failed to block SIGCHLD\\n\");\n // Try our best to restore the signal handlers.\n (void)sigaction(SIGQUIT, &OldSigQuitAction, NULL);\n (void)sigaction(SIGINT, &OldSigIntAction, NULL);\n (void)posix_spawnattr_destroy(&SpawnAttributes);\n return -1;\n }\n }\n ++ActiveThreadCount;\n }\n\n // NOTE: Do not introduce any new `return` statements past this\n // point. It is important that `ActiveThreadCount` always be decremented\n // when leaving this function.\n\n // Make sure the child process uses the default handlers for the\n // following signals rather than inheriting what the parent has.\n sigset_t DefaultSigSet;\n (void)sigemptyset(&DefaultSigSet);\n (void)sigaddset(&DefaultSigSet, SIGQUIT);\n (void)sigaddset(&DefaultSigSet, SIGINT);\n (void)posix_spawnattr_setsigdefault(&SpawnAttributes, &DefaultSigSet);\n // Make sure the child process doesn't block SIGCHLD\n (void)posix_spawnattr_setsigmask(&SpawnAttributes, &OldBlockedSignalsSet);\n short SpawnFlags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;\n (void)posix_spawnattr_setflags(&SpawnAttributes, SpawnFlags);\n\n pid_t Pid;\n char **Environ = environ; // Read from global\n const char *CommandCStr = Command.c_str();\n const char *Argv[] = {\"sh\", \"-c\", CommandCStr, NULL};\n int ErrorCode = 0, ProcessStatus = 0;\n // FIXME: We probably shouldn't hardcode the shell path.\n ErrorCode = posix_spawn(&Pid, \"/bin/sh\", NULL, &SpawnAttributes,\n (char *const *)Argv, Environ);\n (void)posix_spawnattr_destroy(&SpawnAttributes);\n if (!ErrorCode) {\n pid_t SavedPid = Pid;\n do {\n // Repeat until call completes uninterrupted.\n Pid = waitpid(SavedPid, &ProcessStatus, /*options=*/0);\n } while (Pid == -1 && errno == EINTR);\n if (Pid == -1) {\n // Fail for some other reason.\n ProcessStatus = -1;\n }\n } else if (ErrorCode == ENOMEM || ErrorCode == EAGAIN) {\n // Fork failure.\n ProcessStatus = -1;\n } else {\n // Shell execution failure.\n ProcessStatus = W_EXITCODE(127, 0);\n }\n\n // Restore the signal handlers of the current process when the last thread\n // using this function finishes.\n {\n std::lock_guard Lock(SignalMutex);\n --ActiveThreadCount;\n if (ActiveThreadCount == 0) {\n bool FailedRestore = false;\n if (sigaction(SIGINT, &OldSigIntAction, NULL) == -1) {\n Printf(\"Failed to restore SIGINT handling\\n\");\n FailedRestore = true;\n }\n if (sigaction(SIGQUIT, &OldSigQuitAction, NULL) == -1) {\n Printf(\"Failed to restore SIGQUIT handling\\n\");\n FailedRestore = true;\n }\n if (sigprocmask(SIG_BLOCK, &OldBlockedSignalsSet, NULL) == -1) {\n Printf(\"Failed to unblock SIGCHLD\\n\");\n FailedRestore = true;\n }\n if (FailedRestore)\n ProcessStatus = -1;\n }\n }\n return ProcessStatus;\n}\n\n} // namespace fuzzer\n\n#endif // LIBFUZZER_APPLE", "messages": null, "tools": null} {"id": "84f425cf8a2a522f", "category": "code", "domain": "code", "source": "ripgrep", "license": "MIT OR Unlicense", "license_url": "https://spdx.org/licenses/MIT.html", "path": "crates/core/flags/defs.rs", "lang": "rust", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/BurntSushi/ripgrep", "commit": "3fce3b5bb0236da2df6d99672afb8a719642eca7", "collector": "tools/harvest.py"}, "chars": 246352, "sha256": "aa3a04b1973de7ec1319c0bf9ee8f0dc6e6dcc4f340922599e12372e80ba962b", "text": "/*!\nDefines all of the flags available in ripgrep.\n\nEach flag corresponds to a unit struct with a corresponding implementation\nof `Flag`. Note that each implementation of `Flag` might actually have many\npossible manifestations of the same \"flag.\" That is, each implementation of\n`Flag` can have the following flags available to an end user of ripgrep:\n\n* The long flag name.\n* An optional short flag name.\n* An optional negated long flag name.\n* An arbitrarily long list of aliases.\n\nThe idea is that even though there are multiple flags that a user can type,\none implementation of `Flag` corresponds to a single _logical_ flag inside of\nripgrep. For example, `-E`, `--encoding` and `--no-encoding` all manipulate the\nsame encoding state in ripgrep.\n*/\n\nuse std::{path::PathBuf, sync::LazyLock};\n\nuse {anyhow::Context as AnyhowContext, bstr::ByteVec};\n\nuse crate::flags::{\n Category, Flag, FlagValue,\n lowargs::{\n BinaryMode, BoundaryMode, BufferMode, CaseMode, ColorChoice,\n ContextMode, EncodingMode, EngineChoice, GenerateMode, IndexMode,\n LoggingMode, LowArgs, MmapMode, Mode, PatternSource, SearchMode,\n SortMode, SortModeKind, SpecialMode, TypeChange,\n },\n};\n\n#[cfg(test)]\nuse crate::flags::parse::parse_low_raw;\n\nuse super::CompletionType;\n\n/// A list of all flags in ripgrep via implementations of `Flag`.\n///\n/// The order of these flags matter. It determines the order of the flags in\n/// the generated documentation (`-h`, `--help` and the man page) within each\n/// category. (This is why the deprecated flags are last.)\npub(super) const FLAGS: &[&dyn Flag] = &[\n // -e/--regexp and -f/--file should come before anything else in the\n // same category.\n &Regexp,\n &File,\n &AfterContext,\n &BeforeContext,\n &Binary,\n &BlockBuffered,\n &ByteOffset,\n &CaseSensitive,\n &Color,\n &Colors,\n &Column,\n &Context,\n &ContextSeparator,\n &Count,\n &CountMatches,\n &Crlf,\n &Debug,\n &DfaSizeLimit,\n &Encoding,\n &Engine,\n &FieldContextSeparator,\n &FieldMatchSeparator,\n &Files,\n &FilesWithMatches,\n &FilesWithoutMatch,\n &FixedStrings,\n &Follow,\n &Generate,\n &Glob,\n &GlobCaseInsensitive,\n &Heading,\n &Help,\n &Hidden,\n &HostnameBin,\n &HyperlinkFormat,\n &IGlob,\n &IgnoreCase,\n &IgnoreFile,\n &IgnoreFileCaseInsensitive,\n &IncludeZero,\n &Index,\n &IndexCrud,\n &IndexForce,\n &IndexPath,\n &InvertMatch,\n &JSON,\n &LineBuffered,\n &LineNumber,\n &LineNumberNo,\n &LineRegexp,\n &MaxColumns,\n &MaxColumnsPreview,\n &MaxCount,\n &MaxDepth,\n &MaxFilesize,\n &Mmap,\n &Multiline,\n &MultilineDotall,\n &NoConfig,\n &NoIgnore,\n &NoIgnoreDot,\n &NoIgnoreExclude,\n &NoIgnoreFiles,\n &NoIgnoreGlobal,\n &NoIgnoreMessages,\n &NoIgnoreParent,\n &NoIgnoreVcs,\n &NoMessages,\n &NoRequireGit,\n &NoUnicode,\n &Null,\n &NullData,\n &OneFileSystem,\n &OnlyMatching,\n &PathSeparator,\n &Passthru,\n &PCRE2,\n &PCRE2Version,\n &Pre,\n &PreGlob,\n &Pretty,\n &Quiet,\n &RegexSizeLimit,\n &Replace,\n &SearchZip,\n &SmartCase,\n &Sort,\n &Sortr,\n &Stats,\n &StopOnNonmatch,\n &Text,\n &Threads,\n &Trace,\n &Trim,\n &Type,\n &TypeNot,\n &TypeAdd,\n &TypeClear,\n &TypeList,\n &Unrestricted,\n &Version,\n &Vimgrep,\n &WithFilename,\n &WithFilenameNo,\n &WordRegexp,\n // DEPRECATED (make them show up last in their respective categories)\n &AutoHybridRegex,\n &NoPcre2Unicode,\n &SortFiles,\n];\n\nimpl LowArgs {\n /// Returns a flag that does not support indexing, if it's enabled.\n ///\n /// If there aren't any flags enabled that don't support indexing, then\n /// `None` is returned.\n ///\n /// The idea of this routine is to start out very paranoid about what is\n /// allowed to be used when indexing is enabled. Ideally, most or all of\n /// these would eventually become supported.\n pub(super) fn indexing_unsupported_flag(\n &self,\n ) -> Option<&'static dyn Flag> {\n if matches!(self.mode, Mode::Search(SearchMode::FilesWithoutMatch)) {\n return Some(&FilesWithoutMatch);\n }\n if matches!(self.binary, BinaryMode::AsText) {\n return Some(&Binary);\n }\n if !matches!(self.encoding, EncodingMode::Auto) {\n return Some(&Encoding);\n }\n if matches!(self.engine, EngineChoice::PCRE2) {\n return Some(&Engine);\n }\n if self.follow {\n return Some(&Follow);\n }\n if !self.globs.is_empty() {\n return Some(&Glob);\n }\n if self.hidden {\n return Some(&Hidden);\n }\n if !self.iglobs.is_empty() {\n return Some(&Glob);\n }\n if !self.ignore_file.is_empty() {\n return Some(&IgnoreFile);\n }\n if self.no_ignore_dot {\n return Some(&NoIgnoreDot);\n }\n if self.no_ignore_exclude {\n return Some(&NoIgnoreExclude);\n }\n if self.no_ignore_files {\n return Some(&NoIgnoreFiles);\n }\n if self.no_ignore_global {\n return Some(&NoIgnoreGlobal);\n }\n if self.no_ignore_parent {\n return Some(&NoIgnoreParent);\n }\n if self.no_ignore_vcs {\n return Some(&NoIgnoreVcs);\n }\n if self.no_require_git {\n return Some(&NoRequireGit);\n }\n if self.one_file_system {\n return Some(&OneFileSystem);\n }\n if self.pre.is_some() {\n return Some(&Pre);\n }\n if self.search_zip {\n return Some(&SearchZip);\n }\n None\n }\n}\n\n/// -A/--after-context\n#[derive(Debug)]\nstruct AfterContext;\n\nimpl Flag for AfterContext {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_short(&self) -> Option {\n Some(b'A')\n }\n fn name_long(&self) -> &'static str {\n \"after-context\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"NUM\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n \"Show NUM lines after each match.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nShow \\fINUM\\fP lines after each match.\n.sp\nThis overrides the \\flag{passthru} flag and partially overrides the\n\\flag{context} flag.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.context.set_after(convert::usize(&v.unwrap_value())?);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_after_context() {\n let mkctx = |lines| {\n let mut mode = ContextMode::default();\n mode.set_after(lines);\n mode\n };\n\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(ContextMode::default(), args.context);\n\n let args = parse_low_raw([\"--after-context\", \"5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let args = parse_low_raw([\"--after-context=5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let args = parse_low_raw([\"-A\", \"5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let args = parse_low_raw([\"-A5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let args = parse_low_raw([\"-A5\", \"-A10\"]).unwrap();\n assert_eq!(mkctx(10), args.context);\n\n let args = parse_low_raw([\"-A5\", \"-A0\"]).unwrap();\n assert_eq!(mkctx(0), args.context);\n\n let args = parse_low_raw([\"-A5\", \"--passthru\"]).unwrap();\n assert_eq!(ContextMode::Passthru, args.context);\n\n let args = parse_low_raw([\"--passthru\", \"-A5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let n = usize::MAX.to_string();\n let args = parse_low_raw([\"--after-context\", n.as_str()]).unwrap();\n assert_eq!(mkctx(usize::MAX), args.context);\n\n #[cfg(target_pointer_width = \"64\")]\n {\n let n = (u128::from(u64::MAX) + 1).to_string();\n let result = parse_low_raw([\"--after-context\", n.as_str()]);\n assert!(result.is_err(), \"{result:?}\");\n }\n}\n\n/// --auto-hybrid-regex\n#[derive(Debug)]\nstruct AutoHybridRegex;\n\nimpl Flag for AutoHybridRegex {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"auto-hybrid-regex\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-auto-hybrid-regex\")\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n \"(DEPRECATED) Use PCRE2 if appropriate.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nDEPRECATED. Use \\flag{engine} instead.\n.sp\nWhen this flag is used, ripgrep will dynamically choose between supported regex\nengines depending on the features used in a pattern. When ripgrep chooses a\nregex engine, it applies that choice for every regex provided to ripgrep (e.g.,\nvia multiple \\flag{regexp} or \\flag{file} flags).\n.sp\nAs an example of how this flag might behave, ripgrep will attempt to use\nits default finite automata based regex engine whenever the pattern can be\nsuccessfully compiled with that regex engine. If PCRE2 is enabled and if the\npattern given could not be compiled with the default regex engine, then PCRE2\nwill be automatically used for searching. If PCRE2 isn't available, then this\nflag has no effect because there is only one regex engine to choose from.\n.sp\nIn the future, ripgrep may adjust its heuristics for how it decides which\nregex engine to use. In general, the heuristics will be limited to a static\nanalysis of the patterns, and not to any specific runtime behavior observed\nwhile searching files.\n.sp\nThe primary downside of using this flag is that it may not always be obvious\nwhich regex engine ripgrep uses, and thus, the match semantics or performance\nprofile of ripgrep may subtly and unexpectedly change. However, in many cases,\nall regex engines will agree on what constitutes a match and it can be nice\nto transparently support more advanced regex features like look-around and\nbackreferences without explicitly needing to enable them.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let mode = if v.unwrap_switch() {\n EngineChoice::Auto\n } else {\n EngineChoice::Default\n };\n args.engine = mode;\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_auto_hybrid_regex() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(EngineChoice::Default, args.engine);\n\n let args = parse_low_raw([\"--auto-hybrid-regex\"]).unwrap();\n assert_eq!(EngineChoice::Auto, args.engine);\n\n let args =\n parse_low_raw([\"--auto-hybrid-regex\", \"--no-auto-hybrid-regex\"])\n .unwrap();\n assert_eq!(EngineChoice::Default, args.engine);\n\n let args =\n parse_low_raw([\"--no-auto-hybrid-regex\", \"--auto-hybrid-regex\"])\n .unwrap();\n assert_eq!(EngineChoice::Auto, args.engine);\n\n let args = parse_low_raw([\"--auto-hybrid-regex\", \"-P\"]).unwrap();\n assert_eq!(EngineChoice::PCRE2, args.engine);\n\n let args = parse_low_raw([\"-P\", \"--auto-hybrid-regex\"]).unwrap();\n assert_eq!(EngineChoice::Auto, args.engine);\n\n let args =\n parse_low_raw([\"--engine=auto\", \"--auto-hybrid-regex\"]).unwrap();\n assert_eq!(EngineChoice::Auto, args.engine);\n\n let args =\n parse_low_raw([\"--engine=default\", \"--auto-hybrid-regex\"]).unwrap();\n assert_eq!(EngineChoice::Auto, args.engine);\n\n let args =\n parse_low_raw([\"--auto-hybrid-regex\", \"--engine=default\"]).unwrap();\n assert_eq!(EngineChoice::Default, args.engine);\n}\n\n/// -B/--before-context\n#[derive(Debug)]\nstruct BeforeContext;\n\nimpl Flag for BeforeContext {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_short(&self) -> Option {\n Some(b'B')\n }\n fn name_long(&self) -> &'static str {\n \"before-context\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"NUM\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n \"Show NUM lines before each match.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nShow \\fINUM\\fP lines before each match.\n.sp\nThis overrides the \\flag{passthru} flag and partially overrides the\n\\flag{context} flag.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.context.set_before(convert::usize(&v.unwrap_value())?);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_before_context() {\n let mkctx = |lines| {\n let mut mode = ContextMode::default();\n mode.set_before(lines);\n mode\n };\n\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(ContextMode::default(), args.context);\n\n let args = parse_low_raw([\"--before-context\", \"5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let args = parse_low_raw([\"--before-context=5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let args = parse_low_raw([\"-B\", \"5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let args = parse_low_raw([\"-B5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let args = parse_low_raw([\"-B5\", \"-B10\"]).unwrap();\n assert_eq!(mkctx(10), args.context);\n\n let args = parse_low_raw([\"-B5\", \"-B0\"]).unwrap();\n assert_eq!(mkctx(0), args.context);\n\n let args = parse_low_raw([\"-B5\", \"--passthru\"]).unwrap();\n assert_eq!(ContextMode::Passthru, args.context);\n\n let args = parse_low_raw([\"--passthru\", \"-B5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let n = usize::MAX.to_string();\n let args = parse_low_raw([\"--before-context\", n.as_str()]).unwrap();\n assert_eq!(mkctx(usize::MAX), args.context);\n\n #[cfg(target_pointer_width = \"64\")]\n {\n let n = (u128::from(u64::MAX) + 1).to_string();\n let result = parse_low_raw([\"--before-context\", n.as_str()]);\n assert!(result.is_err(), \"{result:?}\");\n }\n}\n\n/// --binary\n#[derive(Debug)]\nstruct Binary;\n\nimpl Flag for Binary {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"binary\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-binary\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n \"Search binary files.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nEnabling this flag will cause ripgrep to search binary files. By default,\nripgrep attempts to automatically skip binary files in order to improve the\nrelevance of results and make the search faster.\n.sp\nBinary files are heuristically detected based on whether they contain a\n\\fBNUL\\fP byte or not. By default (without this flag set), once a \\fBNUL\\fP\nbyte is seen, ripgrep will stop searching the file. Usually, \\fBNUL\\fP bytes\noccur in the beginning of most binary files. If a \\fBNUL\\fP byte occurs after\na match, then ripgrep will not print the match, stop searching that file, and\nemit a warning that some matches are being suppressed.\n.sp\nIn contrast, when this flag is provided, ripgrep will continue searching a\nfile even if a \\fBNUL\\fP byte is found. In particular, if a \\fBNUL\\fP byte is\nfound then ripgrep will continue searching until either a match is found or\nthe end of the file is reached, whichever comes sooner. If a match is found,\nthen ripgrep will stop and print a warning saying that the search stopped\nprematurely.\n.sp\nIf you want ripgrep to search a file without any special \\fBNUL\\fP byte\nhandling at all (and potentially print binary data to stdout), then you should\nuse the \\flag{text} flag.\n.sp\nThe \\flag{binary} flag is a flag for controlling ripgrep's automatic filtering\nmechanism. As such, it does not need to be used when searching a file\nexplicitly or when searching stdin. That is, it is only applicable when\nrecursively searching a directory.\n.sp\nWhen the \\flag{unrestricted} flag is provided for a third time, then this flag\nis automatically enabled.\n.sp\nThis flag overrides the \\flag{text} flag.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.binary = if v.unwrap_switch() {\n BinaryMode::SearchAndSuppress\n } else {\n BinaryMode::Auto\n };\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_binary() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(BinaryMode::Auto, args.binary);\n\n let args = parse_low_raw([\"--binary\"]).unwrap();\n assert_eq!(BinaryMode::SearchAndSuppress, args.binary);\n\n let args = parse_low_raw([\"--binary\", \"--no-binary\"]).unwrap();\n assert_eq!(BinaryMode::Auto, args.binary);\n\n let args = parse_low_raw([\"--no-binary\", \"--binary\"]).unwrap();\n assert_eq!(BinaryMode::SearchAndSuppress, args.binary);\n\n let args = parse_low_raw([\"--binary\", \"-a\"]).unwrap();\n assert_eq!(BinaryMode::AsText, args.binary);\n\n let args = parse_low_raw([\"-a\", \"--binary\"]).unwrap();\n assert_eq!(BinaryMode::SearchAndSuppress, args.binary);\n\n let args = parse_low_raw([\"-a\", \"--no-binary\"]).unwrap();\n assert_eq!(BinaryMode::Auto, args.binary);\n}\n\n/// --block-buffered\n#[derive(Debug)]\nstruct BlockBuffered;\n\nimpl Flag for BlockBuffered {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"block-buffered\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-block-buffered\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n \"Force block buffering.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhen enabled, ripgrep will use block buffering. That is, whenever a matching\nline is found, it will be written to an in-memory buffer and will not be\nwritten to stdout until the buffer reaches a certain size. This is the default\nwhen ripgrep's stdout is redirected to a pipeline or a file. When ripgrep's\nstdout is connected to a tty, line buffering will be used by default. Forcing\nblock buffering can be useful when dumping a large amount of contents to a tty.\n.sp\nThis overrides the \\flag{line-buffered} flag.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.buffer = if v.unwrap_switch() {\n BufferMode::Block\n } else {\n BufferMode::Auto\n };\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_block_buffered() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(BufferMode::Auto, args.buffer);\n\n let args = parse_low_raw([\"--block-buffered\"]).unwrap();\n assert_eq!(BufferMode::Block, args.buffer);\n\n let args =\n parse_low_raw([\"--block-buffered\", \"--no-block-buffered\"]).unwrap();\n assert_eq!(BufferMode::Auto, args.buffer);\n\n let args = parse_low_raw([\"--block-buffered\", \"--line-buffered\"]).unwrap();\n assert_eq!(BufferMode::Line, args.buffer);\n}\n\n/// --byte-offset\n#[derive(Debug)]\nstruct ByteOffset;\n\nimpl Flag for ByteOffset {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'b')\n }\n fn name_long(&self) -> &'static str {\n \"byte-offset\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-byte-offset\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n \"Print the byte offset for each matching line.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nPrint the 0-based byte offset within the input file before each line of output.\nIf \\flag{only-matching} is specified, print the offset of the matched text\nitself.\n.sp\nIf ripgrep does transcoding, then the byte offset is in terms of the result\nof transcoding and not the original data. This applies similarly to other\ntransformations on the data, such as decompression or a \\flag{pre} filter.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.byte_offset = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_byte_offset() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.byte_offset);\n\n let args = parse_low_raw([\"--byte-offset\"]).unwrap();\n assert_eq!(true, args.byte_offset);\n\n let args = parse_low_raw([\"-b\"]).unwrap();\n assert_eq!(true, args.byte_offset);\n\n let args = parse_low_raw([\"--byte-offset\", \"--no-byte-offset\"]).unwrap();\n assert_eq!(false, args.byte_offset);\n\n let args = parse_low_raw([\"--no-byte-offset\", \"-b\"]).unwrap();\n assert_eq!(true, args.byte_offset);\n}\n\n/// -s/--case-sensitive\n#[derive(Debug)]\nstruct CaseSensitive;\n\nimpl Flag for CaseSensitive {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b's')\n }\n fn name_long(&self) -> &'static str {\n \"case-sensitive\"\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"Search case sensitively (default).\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nExecute the search case sensitively. This is the default mode.\n.sp\nThis is a global option that applies to all patterns given to ripgrep.\nIndividual patterns can still be matched case insensitively by using inline\nregex flags. For example, \\fB(?i)abc\\fP will match \\fBabc\\fP case insensitively\neven when this flag is used.\n.sp\nThis flag overrides the \\flag{ignore-case} and \\flag{smart-case} flags.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"flag has no negation\");\n args.case = CaseMode::Sensitive;\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_case_sensitive() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(CaseMode::Sensitive, args.case);\n\n let args = parse_low_raw([\"--case-sensitive\"]).unwrap();\n assert_eq!(CaseMode::Sensitive, args.case);\n\n let args = parse_low_raw([\"-s\"]).unwrap();\n assert_eq!(CaseMode::Sensitive, args.case);\n}\n\n/// --color\n#[derive(Debug)]\nstruct Color;\n\nimpl Flag for Color {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"color\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"WHEN\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n \"When to use color.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis flag controls when to use colors. The default setting is \\fBauto\\fP, which\nmeans ripgrep will try to guess when to use colors. For example, if ripgrep is\nprinting to a tty, then it will use colors, but if it is redirected to a file\nor a pipe, then it will suppress color output.\n.sp\nripgrep will suppress color output by default in some other circumstances as\nwell. These include, but are not limited to:\n.sp\n.IP \\(bu 3n\nWhen the \\fBTERM\\fP environment variable is not set or set to \\fBdumb\\fP.\n.sp\n.IP \\(bu 3n\nWhen the \\fBNO_COLOR\\fP environment variable is set (regardless of value).\n.sp\n.IP \\(bu 3n\nWhen flags that imply no use for colors are given. For example,\n\\flag{vimgrep} and \\flag{json}.\n.\n.PP\nThe possible values for this flag are:\n.sp\n.IP \\fBnever\\fP 10n\nColors will never be used.\n.sp\n.IP \\fBauto\\fP 10n\nThe default. ripgrep tries to be smart.\n.sp\n.IP \\fBalways\\fP 10n\nColors will always be used regardless of where output is sent.\n.sp\n.IP \\fBansi\\fP 10n\nLike 'always', but emits ANSI escapes (even in a Windows console).\n.\n.PP\nThis flag also controls whether hyperlinks are emitted. For example, when\na hyperlink format is specified, hyperlinks won't be used when color is\nsuppressed. If one wants to emit hyperlinks but no colors, then one must use\nthe \\flag{colors} flag to manually set all color styles to \\fBnone\\fP:\n.sp\n.EX\n \\-\\-colors 'path:none' \\\\\n \\-\\-colors 'line:none' \\\\\n \\-\\-colors 'column:none' \\\\\n \\-\\-colors 'match:none' \\\\\n \\-\\-colors 'highlight:none'\n.EE\n.sp\n\"\n }\n fn doc_choices(&self) -> &'static [&'static str] {\n &[\"never\", \"auto\", \"always\", \"ansi\"]\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.color = match convert::str(&v.unwrap_value())? {\n \"never\" => ColorChoice::Never,\n \"auto\" => ColorChoice::Auto,\n \"always\" => ColorChoice::Always,\n \"ansi\" => ColorChoice::Ansi,\n unk => anyhow::bail!(\"choice '{unk}' is unrecognized\"),\n };\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_color() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(ColorChoice::Auto, args.color);\n\n let args = parse_low_raw([\"--color\", \"never\"]).unwrap();\n assert_eq!(ColorChoice::Never, args.color);\n\n let args = parse_low_raw([\"--color\", \"auto\"]).unwrap();\n assert_eq!(ColorChoice::Auto, args.color);\n\n let args = parse_low_raw([\"--color\", \"always\"]).unwrap();\n assert_eq!(ColorChoice::Always, args.color);\n\n let args = parse_low_raw([\"--color\", \"ansi\"]).unwrap();\n assert_eq!(ColorChoice::Ansi, args.color);\n\n let args = parse_low_raw([\"--color=never\"]).unwrap();\n assert_eq!(ColorChoice::Never, args.color);\n\n let args =\n parse_low_raw([\"--color\", \"always\", \"--color\", \"never\"]).unwrap();\n assert_eq!(ColorChoice::Never, args.color);\n\n let args =\n parse_low_raw([\"--color\", \"never\", \"--color\", \"always\"]).unwrap();\n assert_eq!(ColorChoice::Always, args.color);\n\n let result = parse_low_raw([\"--color\", \"foofoo\"]);\n assert!(result.is_err(), \"{result:?}\");\n\n let result = parse_low_raw([\"--color\", \"Always\"]);\n assert!(result.is_err(), \"{result:?}\");\n}\n\n/// --colors\n#[derive(Debug)]\nstruct Colors;\n\nimpl Flag for Colors {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"colors\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"COLOR_SPEC\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n \"Configure color settings and styles.\"\n }\n fn doc_long(&self) -> &'static str {\n r#\"\nThis flag specifies color settings for use in the output. This flag may be\nprovided multiple times. Settings are applied iteratively. Pre-existing color\nlabels are limited to one of eight choices: \\fBred\\fP, \\fBblue\\fP, \\fBgreen\\fP,\n\\fBcyan\\fP, \\fBmagenta\\fP, \\fByellow\\fP, \\fBwhite\\fP and \\fBblack\\fP. Styles\nare limited to \\fBnobold\\fP, \\fBbold\\fP, \\fBnointense\\fP, \\fBintense\\fP,\n\\fBnounderline\\fP, \\fBunderline\\fP, \\fBnoitalic\\fP or \\fBitalic\\fP.\n.sp\nThe format of the flag is\n\\fB{\\fP\\fItype\\fP\\fB}:{\\fP\\fIattribute\\fP\\fB}:{\\fP\\fIvalue\\fP\\fB}\\fP.\n\\fItype\\fP should be one of \\fBpath\\fP, \\fBline\\fP, \\fBcolumn\\fP,\n\\fBhighlight\\fP or \\fBmatch\\fP. \\fIattribute\\fP can be \\fBfg\\fP, \\fBbg\\fP or\n\\fBstyle\\fP. \\fIvalue\\fP is either a color (for \\fBfg\\fP and \\fBbg\\fP) or a\ntext style. A special format, \\fB{\\fP\\fItype\\fP\\fB}:none\\fP, will clear all\ncolor settings for \\fItype\\fP.\n.sp\nFor example, the following command will change the match color to magenta and\nthe background color for line numbers to yellow:\n.sp\n.EX\n rg \\-\\-colors 'match:fg:magenta' \\-\\-colors 'line:bg:yellow'\n.EE\n.sp\nAnother example, the following command will \"highlight\" the non-matching text\nin matching lines:\n.sp\n.EX\n rg \\-\\-colors 'highlight:bg:yellow' \\-\\-colors 'highlight:fg:black'\n.EE\n.sp\nThe \"highlight\" color type is particularly useful for contrasting matching\nlines with surrounding context printed by the \\flag{before-context},\n\\flag{after-context}, \\flag{context} or \\flag{passthru} flags.\n.sp\nExtended colors can be used for \\fIvalue\\fP when the tty supports ANSI color\nsequences. These are specified as either \\fIx\\fP (256-color) or\n.IB x , x , x\n(24-bit truecolor) where \\fIx\\fP is a number between \\fB0\\fP and \\fB255\\fP\ninclusive. \\fIx\\fP may be given as a normal decimal number or a hexadecimal\nnumber, which is prefixed by \\fB0x\\fP.\n.sp\nFor example, the following command will change the match background color to\nthat represented by the rgb value (0,128,255):\n.sp\n.EX\n rg \\-\\-colors 'match:bg:0,128,255'\n.EE\n.sp\nor, equivalently,\n.sp\n.EX\n rg \\-\\-colors 'match:bg:0x0,0x80,0xFF'\n.EE\n.sp\nNote that the \\fBintense\\fP and \\fBnointense\\fP styles will have no effect when\nused alongside these extended color codes.\n\"#\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let v = v.unwrap_value();\n let v = convert::str(&v)?;\n args.colors.push(v.parse()?);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_colors() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert!(args.colors.is_empty());\n\n let args = parse_low_raw([\"--colors\", \"match:fg:magenta\"]).unwrap();\n assert_eq!(args.colors, vec![\"match:fg:magenta\".parse().unwrap()]);\n\n let args = parse_low_raw([\n \"--colors\",\n \"match:fg:magenta\",\n \"--colors\",\n \"line:bg:yellow\",\n ])\n .unwrap();\n assert_eq!(\n args.colors,\n vec![\n \"match:fg:magenta\".parse().unwrap(),\n \"line:bg:yellow\".parse().unwrap()\n ]\n );\n\n let args = parse_low_raw([\"--colors\", \"highlight:bg:240\"]).unwrap();\n assert_eq!(args.colors, vec![\"highlight:bg:240\".parse().unwrap()]);\n\n let args = parse_low_raw([\n \"--colors\",\n \"match:fg:magenta\",\n \"--colors\",\n \"highlight:bg:blue\",\n ])\n .unwrap();\n assert_eq!(\n args.colors,\n vec![\n \"match:fg:magenta\".parse().unwrap(),\n \"highlight:bg:blue\".parse().unwrap()\n ]\n );\n}\n\n/// --column\n#[derive(Debug)]\nstruct Column;\n\nimpl Flag for Column {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"column\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-column\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n \"Show column numbers.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nShow column numbers (1-based). This only shows the column numbers for the first\nmatch on each line. This does not try to account for Unicode. One byte is equal\nto one column. This implies \\flag{line-number}.\n.sp\nWhen \\flag{only-matching} is used, then the column numbers written correspond\nto the start of each match.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.column = Some(v.unwrap_switch());\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_column() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.column);\n\n let args = parse_low_raw([\"--column\"]).unwrap();\n assert_eq!(Some(true), args.column);\n\n let args = parse_low_raw([\"--column\", \"--no-column\"]).unwrap();\n assert_eq!(Some(false), args.column);\n\n let args = parse_low_raw([\"--no-column\", \"--column\"]).unwrap();\n assert_eq!(Some(true), args.column);\n}\n\n/// -C/--context\n#[derive(Debug)]\nstruct Context;\n\nimpl Flag for Context {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_short(&self) -> Option {\n Some(b'C')\n }\n fn name_long(&self) -> &'static str {\n \"context\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"NUM\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Show NUM lines before and after each match.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nShow \\fINUM\\fP lines before and after each match. This is equivalent to\nproviding both the \\flag{before-context} and \\flag{after-context} flags with\nthe same value.\n.sp\nThis overrides the \\flag{passthru} flag. The \\flag{after-context} and\n\\flag{before-context} flags both partially override this flag, regardless of\nthe order. For example, \\fB\\-A2 \\-C1\\fP is equivalent to \\fB\\-A2 \\-B1\\fP.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.context.set_both(convert::usize(&v.unwrap_value())?);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_context() {\n let mkctx = |lines| {\n let mut mode = ContextMode::default();\n mode.set_both(lines);\n mode\n };\n\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(ContextMode::default(), args.context);\n\n let args = parse_low_raw([\"--context\", \"5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let args = parse_low_raw([\"--context=5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let args = parse_low_raw([\"-C\", \"5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let args = parse_low_raw([\"-C5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let args = parse_low_raw([\"-C5\", \"-C10\"]).unwrap();\n assert_eq!(mkctx(10), args.context);\n\n let args = parse_low_raw([\"-C5\", \"-C0\"]).unwrap();\n assert_eq!(mkctx(0), args.context);\n\n let args = parse_low_raw([\"-C5\", \"--passthru\"]).unwrap();\n assert_eq!(ContextMode::Passthru, args.context);\n\n let args = parse_low_raw([\"--passthru\", \"-C5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let n = usize::MAX.to_string();\n let args = parse_low_raw([\"--context\", n.as_str()]).unwrap();\n assert_eq!(mkctx(usize::MAX), args.context);\n\n #[cfg(target_pointer_width = \"64\")]\n {\n let n = (u128::from(u64::MAX) + 1).to_string();\n let result = parse_low_raw([\"--context\", n.as_str()]);\n assert!(result.is_err(), \"{result:?}\");\n }\n\n // Test the interaction between -A/-B and -C. Basically, -A/-B always\n // partially overrides -C, regardless of where they appear relative to\n // each other. This behavior is also how GNU grep works, and it also makes\n // logical sense to me: -A/-B are the more specific flags.\n let args = parse_low_raw([\"-A1\", \"-C5\"]).unwrap();\n let mut mode = ContextMode::default();\n mode.set_after(1);\n mode.set_both(5);\n assert_eq!(mode, args.context);\n assert_eq!((5, 1), args.context.get_limited());\n\n let args = parse_low_raw([\"-B1\", \"-C5\"]).unwrap();\n let mut mode = ContextMode::default();\n mode.set_before(1);\n mode.set_both(5);\n assert_eq!(mode, args.context);\n assert_eq!((1, 5), args.context.get_limited());\n\n let args = parse_low_raw([\"-A1\", \"-B2\", \"-C5\"]).unwrap();\n let mut mode = ContextMode::default();\n mode.set_before(2);\n mode.set_after(1);\n mode.set_both(5);\n assert_eq!(mode, args.context);\n assert_eq!((2, 1), args.context.get_limited());\n\n // These next three are like the ones above, but with -C before -A/-B. This\n // tests that -A and -B only partially override -C. That is, -C1 -A2 is\n // equivalent to -B1 -A2.\n let args = parse_low_raw([\"-C5\", \"-A1\"]).unwrap();\n let mut mode = ContextMode::default();\n mode.set_after(1);\n mode.set_both(5);\n assert_eq!(mode, args.context);\n assert_eq!((5, 1), args.context.get_limited());\n\n let args = parse_low_raw([\"-C5\", \"-B1\"]).unwrap();\n let mut mode = ContextMode::default();\n mode.set_before(1);\n mode.set_both(5);\n assert_eq!(mode, args.context);\n assert_eq!((1, 5), args.context.get_limited());\n\n let args = parse_low_raw([\"-C5\", \"-A1\", \"-B2\"]).unwrap();\n let mut mode = ContextMode::default();\n mode.set_before(2);\n mode.set_after(1);\n mode.set_both(5);\n assert_eq!(mode, args.context);\n assert_eq!((2, 1), args.context.get_limited());\n}\n\n/// --context-separator\n#[derive(Debug)]\nstruct ContextSeparator;\n\nimpl Flag for ContextSeparator {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"context-separator\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-context-separator\")\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"SEPARATOR\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Set the separator for contextual chunks.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThe string used to separate non-contiguous context lines in the output. This is\nonly used when one of the context flags is used (that is, \\flag{after-context},\n\\flag{before-context} or \\flag{context}). Escape sequences like \\fB\\\\x7F\\fP or\n\\fB\\\\t\\fP may be used. The default value is \\fB\\-\\-\\fP.\n.sp\nWhen the context separator is set to an empty string, then a line break\nis still inserted. To completely disable context separators, use the\n\\flag-negate{context-separator} flag.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n use crate::flags::lowargs::ContextSeparator as Separator;\n\n args.context_separator = match v {\n FlagValue::Switch(true) => {\n unreachable!(\"flag can only be disabled\")\n }\n FlagValue::Switch(false) => Separator::disabled(),\n FlagValue::Value(v) => Separator::new(&v)?,\n };\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_context_separator() {\n use bstr::BString;\n\n use crate::flags::lowargs::ContextSeparator as Separator;\n\n let getbytes = |ctxsep: Separator| ctxsep.into_bytes().map(BString::from);\n\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(Some(BString::from(\"--\")), getbytes(args.context_separator));\n\n let args = parse_low_raw([\"--context-separator\", \"XYZ\"]).unwrap();\n assert_eq!(Some(BString::from(\"XYZ\")), getbytes(args.context_separator));\n\n let args = parse_low_raw([\"--no-context-separator\"]).unwrap();\n assert_eq!(None, getbytes(args.context_separator));\n\n let args = parse_low_raw([\n \"--context-separator\",\n \"XYZ\",\n \"--no-context-separator\",\n ])\n .unwrap();\n assert_eq!(None, getbytes(args.context_separator));\n\n let args = parse_low_raw([\n \"--no-context-separator\",\n \"--context-separator\",\n \"XYZ\",\n ])\n .unwrap();\n assert_eq!(Some(BString::from(\"XYZ\")), getbytes(args.context_separator));\n\n // This checks that invalid UTF-8 can be used. This case isn't too tricky\n // to handle, because it passes the invalid UTF-8 as an escape sequence\n // that is itself valid UTF-8. It doesn't become invalid UTF-8 until after\n // the argument is parsed and then unescaped.\n let args = parse_low_raw([\"--context-separator\", r\"\\xFF\"]).unwrap();\n assert_eq!(Some(BString::from(b\"\\xFF\")), getbytes(args.context_separator));\n\n // In this case, we specifically try to pass an invalid UTF-8 argument to\n // the flag. In theory we might be able to support this, but because we do\n // unescaping and because unescaping wants valid UTF-8, we do a UTF-8 check\n // on the value. Since we pass invalid UTF-8, it fails. This demonstrates\n // that the only way to use an invalid UTF-8 separator is by specifying an\n // escape sequence that is itself valid UTF-8.\n #[cfg(unix)]\n {\n use std::{ffi::OsStr, os::unix::ffi::OsStrExt};\n\n let result = parse_low_raw([\n OsStr::from_bytes(b\"--context-separator\"),\n OsStr::from_bytes(&[0xFF]),\n ]);\n assert!(result.is_err(), \"{result:?}\");\n }\n}\n\n/// -c/--count\n#[derive(Debug)]\nstruct Count;\n\nimpl Flag for Count {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'c')\n }\n fn name_long(&self) -> &'static str {\n \"count\"\n }\n fn doc_category(&self) -> Category {\n Category::OutputModes\n }\n fn doc_short(&self) -> &'static str {\n r\"Show count of matching lines for each file.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis flag suppresses normal output and shows the number of lines that match\nthe given patterns for each file searched. Each file containing a match has\nits path and count printed on each line. Note that unless \\flag{multiline} is\nenabled and the pattern(s) given can match over multiple lines, this reports\nthe number of lines that match and not the total number of matches. When\nmultiline mode is enabled and the pattern(s) given can match over multiple\nlines, \\flag{count} is equivalent to \\flag{count-matches}.\n.sp\nIf only one file is given to ripgrep, then only the count is printed if there\nis a match. The \\flag{with-filename} flag can be used to force printing the\nfile path in this case. If you need a count to be printed regardless of whether\nthere is a match, then use \\flag{include-zero}.\n.sp\nNote that it is possible for this flag to have results inconsistent with\nthe output of \\flag{files-with-matches}. Notably, by default, ripgrep tries\nto avoid searching files with binary data. With this flag, ripgrep needs to\nsearch the entire content of files, which may include binary data. But with\n\\flag{files-with-matches}, ripgrep can stop as soon as a match is observed,\nwhich may come well before any binary data. To avoid this inconsistency without\ndisabling binary detection, use the \\flag{binary} flag.\n.sp\nThis overrides the \\flag{count-matches} flag. Note that when \\flag{count}\nis combined with \\flag{only-matching}, then ripgrep behaves as if\n\\flag{count-matches} was given.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--count can only be enabled\");\n args.mode.update(Mode::Search(SearchMode::Count));\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_count() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(Mode::Search(SearchMode::Standard), args.mode);\n\n let args = parse_low_raw([\"--count\"]).unwrap();\n assert_eq!(Mode::Search(SearchMode::Count), args.mode);\n\n let args = parse_low_raw([\"-c\"]).unwrap();\n assert_eq!(Mode::Search(SearchMode::Count), args.mode);\n\n let args = parse_low_raw([\"--count-matches\", \"--count\"]).unwrap();\n assert_eq!(Mode::Search(SearchMode::Count), args.mode);\n\n let args = parse_low_raw([\"--count-matches\", \"-c\"]).unwrap();\n assert_eq!(Mode::Search(SearchMode::Count), args.mode);\n}\n\n/// --count-matches\n#[derive(Debug)]\nstruct CountMatches;\n\nimpl Flag for CountMatches {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"count-matches\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n None\n }\n fn doc_category(&self) -> Category {\n Category::OutputModes\n }\n fn doc_short(&self) -> &'static str {\n r\"Show count of every match for each file.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis flag suppresses normal output and shows the number of individual matches\nof the given patterns for each file searched. Each file containing matches has\nits path and match count printed on each line. Note that this reports the total\nnumber of individual matches and not the number of lines that match.\n.sp\nIf only one file is given to ripgrep, then only the count is printed if there\nis a match. The \\flag{with-filename} flag can be used to force printing the\nfile path in this case.\n.sp\nThis overrides the \\flag{count} flag. Note that when \\flag{count} is combined\nwith \\flag{only-matching}, then ripgrep behaves as if \\flag{count-matches} was\ngiven.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--count-matches can only be enabled\");\n args.mode.update(Mode::Search(SearchMode::CountMatches));\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_count_matches() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(Mode::Search(SearchMode::Standard), args.mode);\n\n let args = parse_low_raw([\"--count-matches\"]).unwrap();\n assert_eq!(Mode::Search(SearchMode::CountMatches), args.mode);\n\n let args = parse_low_raw([\"--count\", \"--count-matches\"]).unwrap();\n assert_eq!(Mode::Search(SearchMode::CountMatches), args.mode);\n\n let args = parse_low_raw([\"-c\", \"--count-matches\"]).unwrap();\n assert_eq!(Mode::Search(SearchMode::CountMatches), args.mode);\n}\n\n/// --crlf\n#[derive(Debug)]\nstruct Crlf;\n\nimpl Flag for Crlf {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"crlf\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-crlf\")\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"Use CRLF line terminators (nice for Windows).\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhen enabled, ripgrep will treat CRLF (\\fB\\\\r\\\\n\\fP) as a line terminator\ninstead of just \\fB\\\\n\\fP.\n.sp\nPrincipally, this permits the line anchor assertions \\fB^\\fP and \\fB$\\fP in\nregex patterns to treat CRLF, CR or LF as line terminators instead of just LF.\nNote that they will never match between a CR and a LF. CRLF is treated as one\nsingle line terminator.\n.sp\nWhen using the default regex engine, CRLF support can also be enabled inside\nthe pattern with the \\fBR\\fP flag. For example, \\fB(?R:$)\\fP will match just\nbefore either CR or LF, but never between CR and LF.\n.sp\nThis flag overrides \\flag{null-data}.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.crlf = v.unwrap_switch();\n if args.crlf {\n args.null_data = false;\n }\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_crlf() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.crlf);\n\n let args = parse_low_raw([\"--crlf\"]).unwrap();\n assert_eq!(true, args.crlf);\n assert_eq!(false, args.null_data);\n\n let args = parse_low_raw([\"--crlf\", \"--null-data\"]).unwrap();\n assert_eq!(false, args.crlf);\n assert_eq!(true, args.null_data);\n\n let args = parse_low_raw([\"--null-data\", \"--crlf\"]).unwrap();\n assert_eq!(true, args.crlf);\n assert_eq!(false, args.null_data);\n\n let args = parse_low_raw([\"--null-data\", \"--no-crlf\"]).unwrap();\n assert_eq!(false, args.crlf);\n assert_eq!(true, args.null_data);\n\n let args = parse_low_raw([\"--null-data\", \"--crlf\", \"--no-crlf\"]).unwrap();\n assert_eq!(false, args.crlf);\n assert_eq!(false, args.null_data);\n}\n\n/// --debug\n#[derive(Debug)]\nstruct Debug;\n\nimpl Flag for Debug {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"debug\"\n }\n fn doc_category(&self) -> Category {\n Category::Logging\n }\n fn doc_short(&self) -> &'static str {\n r\"Show debug messages.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nShow debug messages. Please use this when filing a bug report.\n.sp\nThe \\flag{debug} flag is generally useful for figuring out why ripgrep skipped\nsearching a particular file. The debug messages should mention all files\nskipped and why they were skipped.\n.sp\nTo get even more debug output, use the \\flag{trace} flag, which implies\n\\flag{debug} along with additional trace data.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--debug can only be enabled\");\n args.logging = Some(LoggingMode::Debug);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_debug() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.logging);\n\n let args = parse_low_raw([\"--debug\"]).unwrap();\n assert_eq!(Some(LoggingMode::Debug), args.logging);\n\n let args = parse_low_raw([\"--trace\", \"--debug\"]).unwrap();\n assert_eq!(Some(LoggingMode::Debug), args.logging);\n}\n\n/// --dfa-size-limit\n#[derive(Debug)]\nstruct DfaSizeLimit;\n\nimpl Flag for DfaSizeLimit {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"dfa-size-limit\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"NUM+SUFFIX?\")\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"The upper size limit of the regex DFA.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThe upper size limit of the regex DFA. The default limit is something generous\nfor any single pattern or for many smallish patterns. This should only be\nchanged on very large regex inputs where the (slower) fallback regex engine may\notherwise be used if the limit is reached.\n.sp\nThe input format accepts suffixes of \\fBK\\fP, \\fBM\\fP or \\fBG\\fP which\ncorrespond to kilobytes, megabytes and gigabytes, respectively. If no suffix is\nprovided the input is treated as bytes.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let v = v.unwrap_value();\n args.dfa_size_limit = Some(convert::human_readable_usize(&v)?);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_dfa_size_limit() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.dfa_size_limit);\n\n #[cfg(target_pointer_width = \"64\")]\n {\n let args = parse_low_raw([\"--dfa-size-limit\", \"9G\"]).unwrap();\n assert_eq!(Some(9 * (1 << 30)), args.dfa_size_limit);\n\n let args = parse_low_raw([\"--dfa-size-limit=9G\"]).unwrap();\n assert_eq!(Some(9 * (1 << 30)), args.dfa_size_limit);\n\n let args =\n parse_low_raw([\"--dfa-size-limit=9G\", \"--dfa-size-limit=0\"])\n .unwrap();\n assert_eq!(Some(0), args.dfa_size_limit);\n }\n\n let args = parse_low_raw([\"--dfa-size-limit=0K\"]).unwrap();\n assert_eq!(Some(0), args.dfa_size_limit);\n\n let args = parse_low_raw([\"--dfa-size-limit=0M\"]).unwrap();\n assert_eq!(Some(0), args.dfa_size_limit);\n\n let args = parse_low_raw([\"--dfa-size-limit=0G\"]).unwrap();\n assert_eq!(Some(0), args.dfa_size_limit);\n\n let result = parse_low_raw([\"--dfa-size-limit\", \"9999999999999999999999\"]);\n assert!(result.is_err(), \"{result:?}\");\n\n let result = parse_low_raw([\"--dfa-size-limit\", \"9999999999999999G\"]);\n assert!(result.is_err(), \"{result:?}\");\n}\n\n/// -E/--encoding\n#[derive(Debug)]\nstruct Encoding;\n\nimpl Flag for Encoding {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_short(&self) -> Option {\n Some(b'E')\n }\n fn name_long(&self) -> &'static str {\n \"encoding\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-encoding\")\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"ENCODING\")\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"Specify the text encoding of files to search.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nSpecify the text encoding that ripgrep will use on all files searched. The\ndefault value is \\fBauto\\fP, which will cause ripgrep to do a best effort\nautomatic detection of encoding on a per-file basis. Automatic detection in\nthis case only applies to files that begin with a UTF-8 or UTF-16 byte-order\nmark (BOM). No other automatic detection is performed. One can also specify\n\\fBnone\\fP which will then completely disable BOM sniffing and always result\nin searching the raw bytes, including a BOM if it's present, regardless of its\nencoding.\n.sp\nOther supported values can be found in the list of labels here:\n\\fIhttps://encoding.spec.whatwg.org/#concept-encoding-get\\fP.\n.sp\nFor more details on encoding and how ripgrep deals with it, see \\fBGUIDE.md\\fP.\n.sp\nThe encoding detection that ripgrep uses can be reverted to its automatic mode\nvia the \\flag-negate{encoding} flag.\n\"\n }\n fn completion_type(&self) -> CompletionType {\n CompletionType::Encoding\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let value = match v {\n FlagValue::Value(v) => v,\n FlagValue::Switch(true) => {\n unreachable!(\"--encoding must accept a value\")\n }\n FlagValue::Switch(false) => {\n args.encoding = EncodingMode::Auto;\n return Ok(());\n }\n };\n let label = convert::str(&value)?;\n args.encoding = match label {\n \"auto\" => EncodingMode::Auto,\n \"none\" => EncodingMode::Disabled,\n _ => EncodingMode::Some(grep::searcher::Encoding::new(label)?),\n };\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_encoding() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(EncodingMode::Auto, args.encoding);\n\n let args = parse_low_raw([\"--encoding\", \"auto\"]).unwrap();\n assert_eq!(EncodingMode::Auto, args.encoding);\n\n let args = parse_low_raw([\"--encoding\", \"none\"]).unwrap();\n assert_eq!(EncodingMode::Disabled, args.encoding);\n\n let args = parse_low_raw([\"--encoding=none\"]).unwrap();\n assert_eq!(EncodingMode::Disabled, args.encoding);\n\n let args = parse_low_raw([\"-E\", \"none\"]).unwrap();\n assert_eq!(EncodingMode::Disabled, args.encoding);\n\n let args = parse_low_raw([\"-Enone\"]).unwrap();\n assert_eq!(EncodingMode::Disabled, args.encoding);\n\n let args = parse_low_raw([\"-E\", \"none\", \"--no-encoding\"]).unwrap();\n assert_eq!(EncodingMode::Auto, args.encoding);\n\n let args = parse_low_raw([\"--no-encoding\", \"-E\", \"none\"]).unwrap();\n assert_eq!(EncodingMode::Disabled, args.encoding);\n\n let args = parse_low_raw([\"-E\", \"utf-16\"]).unwrap();\n let enc = grep::searcher::Encoding::new(\"utf-16\").unwrap();\n assert_eq!(EncodingMode::Some(enc), args.encoding);\n\n let args = parse_low_raw([\"-E\", \"utf-16\", \"--no-encoding\"]).unwrap();\n assert_eq!(EncodingMode::Auto, args.encoding);\n\n let result = parse_low_raw([\"-E\", \"foo\"]);\n assert!(result.is_err(), \"{result:?}\");\n}\n\n/// --engine\n#[derive(Debug)]\nstruct Engine;\n\nimpl Flag for Engine {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"engine\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"ENGINE\")\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"Specify which regex engine to use.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nSpecify which regular expression engine to use. When you choose a regex engine,\nit applies that choice for every regex provided to ripgrep (e.g., via multiple\n\\flag{regexp} or \\flag{file} flags).\n.sp\nAccepted values are \\fBdefault\\fP, \\fBpcre2\\fP, or \\fBauto\\fP.\n.sp\nThe default value is \\fBdefault\\fP, which is usually the fastest and should be\ngood for most use cases. The \\fBpcre2\\fP engine is generally useful when you\nwant to use features such as look-around or backreferences. \\fBauto\\fP will\ndynamically choose between supported regex engines depending on the features\nused in a pattern on a best effort basis.\n.sp\nNote that the \\fBpcre2\\fP engine is an optional ripgrep feature. If PCRE2\nwasn't included in your build of ripgrep, then using this flag will result in\nripgrep printing an error message and exiting.\n.sp\nThis overrides previous uses of the \\flag{pcre2} and \\flag{auto-hybrid-regex}\nflags.\n\"\n }\n fn doc_choices(&self) -> &'static [&'static str] {\n &[\"default\", \"pcre2\", \"auto\"]\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let v = v.unwrap_value();\n let string = convert::str(&v)?;\n args.engine = match string {\n \"default\" => EngineChoice::Default,\n \"pcre2\" => EngineChoice::PCRE2,\n \"auto\" => EngineChoice::Auto,\n _ => anyhow::bail!(\"unrecognized regex engine '{string}'\"),\n };\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_engine() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(EngineChoice::Default, args.engine);\n\n let args = parse_low_raw([\"--engine\", \"pcre2\"]).unwrap();\n assert_eq!(EngineChoice::PCRE2, args.engine);\n\n let args = parse_low_raw([\"--engine=pcre2\"]).unwrap();\n assert_eq!(EngineChoice::PCRE2, args.engine);\n\n let args =\n parse_low_raw([\"--auto-hybrid-regex\", \"--engine=pcre2\"]).unwrap();\n assert_eq!(EngineChoice::PCRE2, args.engine);\n\n let args =\n parse_low_raw([\"--engine=pcre2\", \"--auto-hybrid-regex\"]).unwrap();\n assert_eq!(EngineChoice::Auto, args.engine);\n\n let args =\n parse_low_raw([\"--auto-hybrid-regex\", \"--engine=auto\"]).unwrap();\n assert_eq!(EngineChoice::Auto, args.engine);\n\n let args =\n parse_low_raw([\"--auto-hybrid-regex\", \"--engine=default\"]).unwrap();\n assert_eq!(EngineChoice::Default, args.engine);\n\n let args =\n parse_low_raw([\"--engine=pcre2\", \"--no-auto-hybrid-regex\"]).unwrap();\n assert_eq!(EngineChoice::Default, args.engine);\n}\n\n/// --field-context-separator\n#[derive(Debug)]\nstruct FieldContextSeparator;\n\nimpl Flag for FieldContextSeparator {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"field-context-separator\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"SEPARATOR\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Set the field context separator.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nSet the field context separator. This separator is only used when printing\ncontextual lines. It is used to delimit file paths, line numbers, columns and\nthe contextual line itself. The separator may be any number of bytes, including\nzero. Escape sequences like \\fB\\\\x7F\\fP or \\fB\\\\t\\fP may be used.\n.sp\nThe \\fB-\\fP character is the default value.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n use crate::flags::lowargs::FieldContextSeparator as Separator;\n\n args.field_context_separator = Separator::new(&v.unwrap_value())?;\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_field_context_separator() {\n use bstr::BString;\n\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(BString::from(\"-\"), args.field_context_separator.into_bytes());\n\n let args = parse_low_raw([\"--field-context-separator\", \"XYZ\"]).unwrap();\n assert_eq!(\n BString::from(\"XYZ\"),\n args.field_context_separator.into_bytes()\n );\n\n let args = parse_low_raw([\"--field-context-separator=XYZ\"]).unwrap();\n assert_eq!(\n BString::from(\"XYZ\"),\n args.field_context_separator.into_bytes()\n );\n\n let args = parse_low_raw([\n \"--field-context-separator\",\n \"XYZ\",\n \"--field-context-separator\",\n \"ABC\",\n ])\n .unwrap();\n assert_eq!(\n BString::from(\"ABC\"),\n args.field_context_separator.into_bytes()\n );\n\n let args = parse_low_raw([\"--field-context-separator\", r\"\\t\"]).unwrap();\n assert_eq!(BString::from(\"\\t\"), args.field_context_separator.into_bytes());\n\n let args = parse_low_raw([\"--field-context-separator\", r\"\\x00\"]).unwrap();\n assert_eq!(\n BString::from(\"\\x00\"),\n args.field_context_separator.into_bytes()\n );\n\n // This checks that invalid UTF-8 can be used. This case isn't too tricky\n // to handle, because it passes the invalid UTF-8 as an escape sequence\n // that is itself valid UTF-8. It doesn't become invalid UTF-8 until after\n // the argument is parsed and then unescaped.\n let args = parse_low_raw([\"--field-context-separator\", r\"\\xFF\"]).unwrap();\n assert_eq!(\n BString::from(b\"\\xFF\"),\n args.field_context_separator.into_bytes()\n );\n\n // In this case, we specifically try to pass an invalid UTF-8 argument to\n // the flag. In theory we might be able to support this, but because we do\n // unescaping and because unescaping wants valid UTF-8, we do a UTF-8 check\n // on the value. Since we pass invalid UTF-8, it fails. This demonstrates\n // that the only way to use an invalid UTF-8 separator is by specifying an\n // escape sequence that is itself valid UTF-8.\n #[cfg(unix)]\n {\n use std::{ffi::OsStr, os::unix::ffi::OsStrExt};\n\n let result = parse_low_raw([\n OsStr::from_bytes(b\"--field-context-separator\"),\n OsStr::from_bytes(&[0xFF]),\n ]);\n assert!(result.is_err(), \"{result:?}\");\n }\n}\n\n/// --field-match-separator\n#[derive(Debug)]\nstruct FieldMatchSeparator;\n\nimpl Flag for FieldMatchSeparator {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"field-match-separator\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"SEPARATOR\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Set the field match separator.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nSet the field match separator. This separator is only used when printing\nmatching lines. It is used to delimit file paths, line numbers, columns and the\nmatching line itself. The separator may be any number of bytes, including zero.\nEscape sequences like \\fB\\\\x7F\\fP or \\fB\\\\t\\fP may be used.\n.sp\nThe \\fB:\\fP character is the default value.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n use crate::flags::lowargs::FieldMatchSeparator as Separator;\n\n args.field_match_separator = Separator::new(&v.unwrap_value())?;\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_field_match_separator() {\n use bstr::BString;\n\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(BString::from(\":\"), args.field_match_separator.into_bytes());\n\n let args = parse_low_raw([\"--field-match-separator\", \"XYZ\"]).unwrap();\n assert_eq!(BString::from(\"XYZ\"), args.field_match_separator.into_bytes());\n\n let args = parse_low_raw([\"--field-match-separator=XYZ\"]).unwrap();\n assert_eq!(BString::from(\"XYZ\"), args.field_match_separator.into_bytes());\n\n let args = parse_low_raw([\n \"--field-match-separator\",\n \"XYZ\",\n \"--field-match-separator\",\n \"ABC\",\n ])\n .unwrap();\n assert_eq!(BString::from(\"ABC\"), args.field_match_separator.into_bytes());\n\n let args = parse_low_raw([\"--field-match-separator\", r\"\\t\"]).unwrap();\n assert_eq!(BString::from(\"\\t\"), args.field_match_separator.into_bytes());\n\n let args = parse_low_raw([\"--field-match-separator\", r\"\\x00\"]).unwrap();\n assert_eq!(BString::from(\"\\x00\"), args.field_match_separator.into_bytes());\n\n // This checks that invalid UTF-8 can be used. This case isn't too tricky\n // to handle, because it passes the invalid UTF-8 as an escape sequence\n // that is itself valid UTF-8. It doesn't become invalid UTF-8 until after\n // the argument is parsed and then unescaped.\n let args = parse_low_raw([\"--field-match-separator\", r\"\\xFF\"]).unwrap();\n assert_eq!(\n BString::from(b\"\\xFF\"),\n args.field_match_separator.into_bytes()\n );\n\n // In this case, we specifically try to pass an invalid UTF-8 argument to\n // the flag. In theory we might be able to support this, but because we do\n // unescaping and because unescaping wants valid UTF-8, we do a UTF-8 check\n // on the value. Since we pass invalid UTF-8, it fails. This demonstrates\n // that the only way to use an invalid UTF-8 separator is by specifying an\n // escape sequence that is itself valid UTF-8.\n #[cfg(unix)]\n {\n use std::{ffi::OsStr, os::unix::ffi::OsStrExt};\n\n let result = parse_low_raw([\n OsStr::from_bytes(b\"--field-match-separator\"),\n OsStr::from_bytes(&[0xFF]),\n ]);\n assert!(result.is_err(), \"{result:?}\");\n }\n}\n\n/// -f/--file\n#[derive(Debug)]\nstruct File;\n\nimpl Flag for File {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_short(&self) -> Option {\n Some(b'f')\n }\n fn name_long(&self) -> &'static str {\n \"file\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"PATTERNFILE\")\n }\n fn doc_category(&self) -> Category {\n Category::Input\n }\n fn doc_short(&self) -> &'static str {\n r\"Search for patterns from the given file.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nSearch for patterns from the given file, with one pattern per line. When this\nflag is used multiple times or in combination with the \\flag{regexp} flag, then\nall patterns provided are searched. Empty pattern lines will match all input\nlines, and the newline is not counted as part of the pattern.\n.sp\nA line is printed if and only if it matches at least one of the patterns.\n.sp\nWhen \\fIPATTERNFILE\\fP is \\fB-\\fP, then \\fBstdin\\fP will be read for the\npatterns.\n.sp\nWhen \\flag{file} or \\flag{regexp} is used, then ripgrep treats all positional\narguments as files or directories to search.\n\"\n }\n fn completion_type(&self) -> CompletionType {\n CompletionType::Filename\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let path = PathBuf::from(v.unwrap_value());\n args.patterns.push(PatternSource::File(path));\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_file() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(Vec::::new(), args.patterns);\n\n let args = parse_low_raw([\"--file\", \"foo\"]).unwrap();\n assert_eq!(vec![PatternSource::File(PathBuf::from(\"foo\"))], args.patterns);\n\n let args = parse_low_raw([\"--file=foo\"]).unwrap();\n assert_eq!(vec![PatternSource::File(PathBuf::from(\"foo\"))], args.patterns);\n\n let args = parse_low_raw([\"-f\", \"foo\"]).unwrap();\n assert_eq!(vec![PatternSource::File(PathBuf::from(\"foo\"))], args.patterns);\n\n let args = parse_low_raw([\"-ffoo\"]).unwrap();\n assert_eq!(vec![PatternSource::File(PathBuf::from(\"foo\"))], args.patterns);\n\n let args = parse_low_raw([\"--file\", \"-foo\"]).unwrap();\n assert_eq!(\n vec![PatternSource::File(PathBuf::from(\"-foo\"))],\n args.patterns\n );\n\n let args = parse_low_raw([\"--file=-foo\"]).unwrap();\n assert_eq!(\n vec![PatternSource::File(PathBuf::from(\"-foo\"))],\n args.patterns\n );\n\n let args = parse_low_raw([\"-f\", \"-foo\"]).unwrap();\n assert_eq!(\n vec![PatternSource::File(PathBuf::from(\"-foo\"))],\n args.patterns\n );\n\n let args = parse_low_raw([\"-f-foo\"]).unwrap();\n assert_eq!(\n vec![PatternSource::File(PathBuf::from(\"-foo\"))],\n args.patterns\n );\n\n let args = parse_low_raw([\"--file=foo\", \"--file\", \"bar\"]).unwrap();\n assert_eq!(\n vec![\n PatternSource::File(PathBuf::from(\"foo\")),\n PatternSource::File(PathBuf::from(\"bar\"))\n ],\n args.patterns\n );\n\n // We permit path arguments to be invalid UTF-8. So test that. Some of\n // these cases are tricky and depend on lexopt doing the right thing.\n //\n // We probably should add tests for this handling on Windows too, but paths\n // that are invalid UTF-16 appear incredibly rare in the Windows world.\n #[cfg(unix)]\n {\n use std::{\n ffi::{OsStr, OsString},\n os::unix::ffi::{OsStrExt, OsStringExt},\n };\n\n let bytes = &[b'A', 0xFF, b'Z'][..];\n let path = PathBuf::from(OsString::from_vec(bytes.to_vec()));\n\n let args = parse_low_raw([\n OsStr::from_bytes(b\"--file\"),\n OsStr::from_bytes(bytes),\n ])\n .unwrap();\n assert_eq!(vec![PatternSource::File(path.clone())], args.patterns);\n\n let args = parse_low_raw([\n OsStr::from_bytes(b\"-f\"),\n OsStr::from_bytes(bytes),\n ])\n .unwrap();\n assert_eq!(vec![PatternSource::File(path.clone())], args.patterns);\n\n let mut bytes = b\"--file=A\".to_vec();\n bytes.push(0xFF);\n bytes.push(b'Z');\n let args = parse_low_raw([OsStr::from_bytes(&bytes)]).unwrap();\n assert_eq!(vec![PatternSource::File(path.clone())], args.patterns);\n\n let mut bytes = b\"-fA\".to_vec();\n bytes.push(0xFF);\n bytes.push(b'Z');\n let args = parse_low_raw([OsStr::from_bytes(&bytes)]).unwrap();\n assert_eq!(vec![PatternSource::File(path.clone())], args.patterns);\n }\n}\n\n/// --files\n#[derive(Debug)]\nstruct Files;\n\nimpl Flag for Files {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"files\"\n }\n fn doc_category(&self) -> Category {\n Category::OtherBehaviors\n }\n fn doc_short(&self) -> &'static str {\n r\"Print each file that would be searched.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nPrint each file that would be searched without actually performing the search.\nThis is useful to determine whether a particular file is being searched or not.\n.sp\nThis overrides \\flag{type-list}.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch());\n args.mode.update(Mode::Files);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_files() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(Mode::Search(SearchMode::Standard), args.mode);\n\n let args = parse_low_raw([\"--files\"]).unwrap();\n assert_eq!(Mode::Files, args.mode);\n}\n\n/// -l/--files-with-matches\n#[derive(Debug)]\nstruct FilesWithMatches;\n\nimpl Flag for FilesWithMatches {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'l')\n }\n fn name_long(&self) -> &'static str {\n \"files-with-matches\"\n }\n fn doc_category(&self) -> Category {\n Category::OutputModes\n }\n fn doc_short(&self) -> &'static str {\n r\"Print the paths with at least one match.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nPrint only the paths with at least one match and suppress match contents.\n.sp\nNote that it is possible for this flag to have results inconsistent with the\noutput of \\flag{count}. Notably, by default, ripgrep tries to avoid searching\nfiles with binary data. With this flag, ripgrep might stop searching before\nthe binary data is observed. But with \\flag{count}, ripgrep has to search the\nentire contents to determine the match count, which means it might see binary\ndata that causes it to skip searching that file. To avoid this inconsistency\nwithout disabling binary detection, use the \\flag{binary} flag.\n.sp\nThis overrides \\flag{files-without-match}.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--files-with-matches can only be enabled\");\n args.mode.update(Mode::Search(SearchMode::FilesWithMatches));\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_files_with_matches() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(Mode::Search(SearchMode::Standard), args.mode);\n\n let args = parse_low_raw([\"--files-with-matches\"]).unwrap();\n assert_eq!(Mode::Search(SearchMode::FilesWithMatches), args.mode);\n\n let args = parse_low_raw([\"-l\"]).unwrap();\n assert_eq!(Mode::Search(SearchMode::FilesWithMatches), args.mode);\n}\n\n/// -l/--files-without-match\n#[derive(Debug)]\nstruct FilesWithoutMatch;\n\nimpl Flag for FilesWithoutMatch {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"files-without-match\"\n }\n fn doc_category(&self) -> Category {\n Category::OutputModes\n }\n fn doc_short(&self) -> &'static str {\n r\"Print the paths that contain zero matches.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nPrint the paths that contain zero matches and suppress match contents.\n.sp\nThis overrides \\flag{files-with-matches}.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(\n v.unwrap_switch(),\n \"--files-without-match can only be enabled\"\n );\n args.mode.update(Mode::Search(SearchMode::FilesWithoutMatch));\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_files_without_match() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(Mode::Search(SearchMode::Standard), args.mode);\n\n let args = parse_low_raw([\"--files-without-match\"]).unwrap();\n assert_eq!(Mode::Search(SearchMode::FilesWithoutMatch), args.mode);\n\n let args =\n parse_low_raw([\"--files-with-matches\", \"--files-without-match\"])\n .unwrap();\n assert_eq!(Mode::Search(SearchMode::FilesWithoutMatch), args.mode);\n\n let args =\n parse_low_raw([\"--files-without-match\", \"--files-with-matches\"])\n .unwrap();\n assert_eq!(Mode::Search(SearchMode::FilesWithMatches), args.mode);\n}\n\n/// -F/--fixed-strings\n#[derive(Debug)]\nstruct FixedStrings;\n\nimpl Flag for FixedStrings {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'F')\n }\n fn name_long(&self) -> &'static str {\n \"fixed-strings\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-fixed-strings\")\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"Treat all patterns as literals.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nTreat all patterns as literals instead of as regular expressions. When this\nflag is used, special regular expression meta characters such as \\fB.(){}*+\\fP\nshould not need be escaped.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.fixed_strings = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_fixed_strings() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.fixed_strings);\n\n let args = parse_low_raw([\"--fixed-strings\"]).unwrap();\n assert_eq!(true, args.fixed_strings);\n\n let args = parse_low_raw([\"-F\"]).unwrap();\n assert_eq!(true, args.fixed_strings);\n\n let args = parse_low_raw([\"-F\", \"--no-fixed-strings\"]).unwrap();\n assert_eq!(false, args.fixed_strings);\n\n let args = parse_low_raw([\"--no-fixed-strings\", \"-F\"]).unwrap();\n assert_eq!(true, args.fixed_strings);\n}\n\n/// -L/--follow\n#[derive(Debug)]\nstruct Follow;\n\nimpl Flag for Follow {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'L')\n }\n fn name_long(&self) -> &'static str {\n \"follow\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-follow\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Follow symbolic links.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis flag instructs ripgrep to follow symbolic links while traversing\ndirectories. This behavior is disabled by default. Note that ripgrep will\ncheck for symbolic link loops and report errors if it finds one. ripgrep will\nalso report errors for broken links. To suppress error messages, use the\n\\flag{no-messages} flag.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.follow = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_follow() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.follow);\n\n let args = parse_low_raw([\"--follow\"]).unwrap();\n assert_eq!(true, args.follow);\n\n let args = parse_low_raw([\"-L\"]).unwrap();\n assert_eq!(true, args.follow);\n\n let args = parse_low_raw([\"-L\", \"--no-follow\"]).unwrap();\n assert_eq!(false, args.follow);\n\n let args = parse_low_raw([\"--no-follow\", \"-L\"]).unwrap();\n assert_eq!(true, args.follow);\n}\n\n/// --generate\n#[derive(Debug)]\nstruct Generate;\n\nimpl Flag for Generate {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"generate\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"KIND\")\n }\n fn doc_category(&self) -> Category {\n Category::OtherBehaviors\n }\n fn doc_short(&self) -> &'static str {\n r\"Generate man pages and completion scripts.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis flag instructs ripgrep to generate some special kind of output identified\nby \\fIKIND\\fP and then quit without searching. \\fIKIND\\fP can be one of the\nfollowing values:\n.sp\n.TP 15\n\\fBman\\fP\nGenerates a manual page for ripgrep in the \\fBroff\\fP format.\n.TP 15\n\\fBcomplete\\-bash\\fP\nGenerates a completion script for the \\fBbash\\fP shell.\n.TP 15\n\\fBcomplete\\-zsh\\fP\nGenerates a completion script for the \\fBzsh\\fP shell.\n.TP 15\n\\fBcomplete\\-fish\\fP\nGenerates a completion script for the \\fBfish\\fP shell.\n.TP 15\n\\fBcomplete\\-powershell\\fP\nGenerates a completion script for PowerShell.\n.PP\nThe output is written to \\fBstdout\\fP. The list above may expand over time.\n\"\n }\n fn doc_choices(&self) -> &'static [&'static str] {\n &[\n \"man\",\n \"complete-bash\",\n \"complete-zsh\",\n \"complete-fish\",\n \"complete-powershell\",\n ]\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let genmode = match convert::str(&v.unwrap_value())? {\n \"man\" => GenerateMode::Man,\n \"complete-bash\" => GenerateMode::CompleteBash,\n \"complete-zsh\" => GenerateMode::CompleteZsh,\n \"complete-fish\" => GenerateMode::CompleteFish,\n \"complete-powershell\" => GenerateMode::CompletePowerShell,\n unk => anyhow::bail!(\"choice '{unk}' is unrecognized\"),\n };\n args.mode.update(Mode::Generate(genmode));\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_generate() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(Mode::Search(SearchMode::Standard), args.mode);\n\n let args = parse_low_raw([\"--generate\", \"man\"]).unwrap();\n assert_eq!(Mode::Generate(GenerateMode::Man), args.mode);\n\n let args = parse_low_raw([\"--generate\", \"complete-bash\"]).unwrap();\n assert_eq!(Mode::Generate(GenerateMode::CompleteBash), args.mode);\n\n let args = parse_low_raw([\"--generate\", \"complete-zsh\"]).unwrap();\n assert_eq!(Mode::Generate(GenerateMode::CompleteZsh), args.mode);\n\n let args = parse_low_raw([\"--generate\", \"complete-fish\"]).unwrap();\n assert_eq!(Mode::Generate(GenerateMode::CompleteFish), args.mode);\n\n let args = parse_low_raw([\"--generate\", \"complete-powershell\"]).unwrap();\n assert_eq!(Mode::Generate(GenerateMode::CompletePowerShell), args.mode);\n\n let args =\n parse_low_raw([\"--generate\", \"complete-bash\", \"--generate=man\"])\n .unwrap();\n assert_eq!(Mode::Generate(GenerateMode::Man), args.mode);\n\n let args = parse_low_raw([\"--generate\", \"man\", \"-l\"]).unwrap();\n assert_eq!(Mode::Search(SearchMode::FilesWithMatches), args.mode);\n\n // An interesting quirk of how the modes override each other that lets\n // you get back to the \"default\" mode of searching.\n let args =\n parse_low_raw([\"--generate\", \"man\", \"--json\", \"--no-json\"]).unwrap();\n assert_eq!(Mode::Search(SearchMode::Standard), args.mode);\n}\n\n/// -g/--glob\n#[derive(Debug)]\nstruct Glob;\n\nimpl Flag for Glob {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_short(&self) -> Option {\n Some(b'g')\n }\n fn name_long(&self) -> &'static str {\n \"glob\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"GLOB\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Include or exclude file paths.\"\n }\n fn doc_long(&self) -> &'static str {\n r#\"\nInclude or exclude files and directories for searching that match the given\nglob. This always overrides any other ignore logic. Multiple glob flags may\nbe used. Globbing rules match \\fB.gitignore\\fP globs. Precede a glob with a\n\\fB!\\fP to exclude it. If multiple globs match a file or directory, the glob\ngiven later in the command line takes precedence.\n.sp\nAs an extension, globs support specifying alternatives:\n.BI \"\\-g '\" ab{c,d}* '\nis equivalent to\n.BI \"\\-g \" \"abc \" \"\\-g \" abd.\nEmpty alternatives like\n.BI \"\\-g '\" ab{,c} '\nare not currently supported. Note that this syntax extension is also currently\nenabled in \\fBgitignore\\fP files, even though this syntax isn't supported by\ngit itself. ripgrep may disable this syntax extension in gitignore files, but\nit will always remain available via the \\flag{glob} flag.\n.sp\nWhen this flag is set, every file and directory is applied to it to test for\na match. For example, if you only want to search in a particular directory\n\\fIfoo\\fP, then\n.BI \"\\-g \" foo\nis incorrect because \\fIfoo/bar\\fP does not match\nthe glob \\fIfoo\\fP. Instead, you should use\n.BI \"\\-g '\" foo/** '.\n\"#\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let glob = convert::string(v.unwrap_value())?;\n args.globs.push(glob);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_glob() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(Vec::::new(), args.globs);\n\n let args = parse_low_raw([\"--glob\", \"foo\"]).unwrap();\n assert_eq!(vec![\"foo\".to_string()], args.globs);\n\n let args = parse_low_raw([\"--glob=foo\"]).unwrap();\n assert_eq!(vec![\"foo\".to_string()], args.globs);\n\n let args = parse_low_raw([\"-g\", \"foo\"]).unwrap();\n assert_eq!(vec![\"foo\".to_string()], args.globs);\n\n let args = parse_low_raw([\"-gfoo\"]).unwrap();\n assert_eq!(vec![\"foo\".to_string()], args.globs);\n\n let args = parse_low_raw([\"--glob\", \"-foo\"]).unwrap();\n assert_eq!(vec![\"-foo\".to_string()], args.globs);\n\n let args = parse_low_raw([\"--glob=-foo\"]).unwrap();\n assert_eq!(vec![\"-foo\".to_string()], args.globs);\n\n let args = parse_low_raw([\"-g\", \"-foo\"]).unwrap();\n assert_eq!(vec![\"-foo\".to_string()], args.globs);\n\n let args = parse_low_raw([\"-g-foo\"]).unwrap();\n assert_eq!(vec![\"-foo\".to_string()], args.globs);\n}\n\n/// --glob-case-insensitive\n#[derive(Debug)]\nstruct GlobCaseInsensitive;\n\nimpl Flag for GlobCaseInsensitive {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"glob-case-insensitive\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-glob-case-insensitive\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Process all glob patterns case insensitively.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nProcess all glob patterns given with the \\flag{glob} flag case insensitively.\nThis effectively treats \\flag{glob} as \\flag{iglob}.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.glob_case_insensitive = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_glob_case_insensitive() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.glob_case_insensitive);\n\n let args = parse_low_raw([\"--glob-case-insensitive\"]).unwrap();\n assert_eq!(true, args.glob_case_insensitive);\n\n let args = parse_low_raw([\n \"--glob-case-insensitive\",\n \"--no-glob-case-insensitive\",\n ])\n .unwrap();\n assert_eq!(false, args.glob_case_insensitive);\n\n let args = parse_low_raw([\n \"--no-glob-case-insensitive\",\n \"--glob-case-insensitive\",\n ])\n .unwrap();\n assert_eq!(true, args.glob_case_insensitive);\n}\n\n/// --heading\n#[derive(Debug)]\nstruct Heading;\n\nimpl Flag for Heading {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"heading\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-heading\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Print matches grouped by each file.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis flag prints the file path above clusters of matches from each file instead\nof printing the file path as a prefix for each matched line.\n.sp\nThis is the default mode when printing to a tty.\n.sp\nWhen \\fBstdout\\fP is not a tty, then ripgrep will default to the standard\ngrep-like format. One can force this format in Unix-like environments by\npiping the output of ripgrep to \\fBcat\\fP. For example, \\fBrg\\fP \\fIfoo\\fP \\fB|\ncat\\fP.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.heading = Some(v.unwrap_switch());\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_heading() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.heading);\n\n let args = parse_low_raw([\"--heading\"]).unwrap();\n assert_eq!(Some(true), args.heading);\n\n let args = parse_low_raw([\"--no-heading\"]).unwrap();\n assert_eq!(Some(false), args.heading);\n\n let args = parse_low_raw([\"--heading\", \"--no-heading\"]).unwrap();\n assert_eq!(Some(false), args.heading);\n\n let args = parse_low_raw([\"--no-heading\", \"--heading\"]).unwrap();\n assert_eq!(Some(true), args.heading);\n}\n\n/// -h/--help\n#[derive(Debug)]\nstruct Help;\n\nimpl Flag for Help {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"help\"\n }\n fn name_short(&self) -> Option {\n Some(b'h')\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Show help output.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis flag prints the help output for ripgrep.\n.sp\nUnlike most other flags, the behavior of the short flag, \\fB\\-h\\fP, and the\nlong flag, \\fB\\-\\-help\\fP, is different. The short flag will show a condensed\nhelp output while the long flag will show a verbose help output. The verbose\nhelp output has complete documentation, where as the condensed help output will\nshow only a single line for every flag.\n\"\n }\n\n fn update(&self, v: FlagValue, _: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--help has no negation\");\n // Since this flag has different semantics for -h and --help and the\n // Flag trait doesn't support encoding this sort of thing, we handle it\n // as a special case in the parser.\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_help() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.special);\n\n let args = parse_low_raw([\"-h\"]).unwrap();\n assert_eq!(Some(SpecialMode::HelpShort), args.special);\n\n let args = parse_low_raw([\"--help\"]).unwrap();\n assert_eq!(Some(SpecialMode::HelpLong), args.special);\n\n let args = parse_low_raw([\"-h\", \"--help\"]).unwrap();\n assert_eq!(Some(SpecialMode::HelpLong), args.special);\n\n let args = parse_low_raw([\"--help\", \"-h\"]).unwrap();\n assert_eq!(Some(SpecialMode::HelpShort), args.special);\n}\n\n/// -./--hidden\n#[derive(Debug)]\nstruct Hidden;\n\nimpl Flag for Hidden {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'.')\n }\n fn name_long(&self) -> &'static str {\n \"hidden\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-hidden\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Search hidden files and directories.\"\n }\n fn doc_long(&self) -> &'static str {\n r#\"\nSearch hidden files and directories. By default, hidden files and directories\nare skipped. Note that if a hidden file or a directory is whitelisted in\nan ignore file, then it will be searched even if this flag isn't provided.\nSimilarly if a hidden file or directory is given explicitly as an argument to\nripgrep.\n.sp\nA file or directory is considered hidden if its base name starts with a dot\ncharacter (\\fB.\\fP). On operating systems which support a \"hidden\" file\nattribute, like Windows, files with this attribute are also considered hidden.\n.sp\nNote that \\flag{hidden} will include files and folders like \\fB.git\\fP\nregardless of \\flag{no-ignore-vcs}. To exclude such paths when using\n\\flag{hidden}, you must explicitly ignore them using another flag or ignore\nfile.\n\"#\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.hidden = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_hidden() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.hidden);\n\n let args = parse_low_raw([\"--hidden\"]).unwrap();\n assert_eq!(true, args.hidden);\n\n let args = parse_low_raw([\"-.\"]).unwrap();\n assert_eq!(true, args.hidden);\n\n let args = parse_low_raw([\"-.\", \"--no-hidden\"]).unwrap();\n assert_eq!(false, args.hidden);\n\n let args = parse_low_raw([\"--no-hidden\", \"-.\"]).unwrap();\n assert_eq!(true, args.hidden);\n}\n\n/// --hostname-bin\n#[derive(Debug)]\nstruct HostnameBin;\n\nimpl Flag for HostnameBin {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"hostname-bin\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"COMMAND\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Run a program to get this system's hostname.\"\n }\n fn doc_long(&self) -> &'static str {\n r#\"\nThis flag controls how ripgrep determines this system's hostname. The flag's\nvalue should correspond to an executable (either a path or something that can\nbe found via your system's \\fBPATH\\fP environment variable). When set, ripgrep\nwill run this executable, with no arguments, and treat its output (with leading\nand trailing whitespace stripped) as your system's hostname.\n.sp\nWhen not set (the default, or the empty string), ripgrep will try to\nautomatically detect your system's hostname. On Unix, this corresponds\nto calling \\fBgethostname\\fP. On Windows, this corresponds to calling\n\\fBGetComputerNameExW\\fP to fetch the system's \"physical DNS hostname.\"\n.sp\nripgrep uses your system's hostname for producing hyperlinks.\n\"#\n }\n fn completion_type(&self) -> CompletionType {\n CompletionType::Executable\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let path = PathBuf::from(v.unwrap_value());\n args.hostname_bin =\n if path.as_os_str().is_empty() { None } else { Some(path) };\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_hostname_bin() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.hostname_bin);\n\n let args = parse_low_raw([\"--hostname-bin\", \"foo\"]).unwrap();\n assert_eq!(Some(PathBuf::from(\"foo\")), args.hostname_bin);\n\n let args = parse_low_raw([\"--hostname-bin=foo\"]).unwrap();\n assert_eq!(Some(PathBuf::from(\"foo\")), args.hostname_bin);\n}\n\n/// --hyperlink-format\n#[derive(Debug)]\nstruct HyperlinkFormat;\n\nimpl Flag for HyperlinkFormat {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"hyperlink-format\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"FORMAT\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Set the format of hyperlinks.\"\n }\n fn doc_long(&self) -> &'static str {\n static DOC: LazyLock = LazyLock::new(|| {\n let mut doc = String::new();\n doc.push_str(\n r#\"\nSet the format of hyperlinks to use when printing results. Hyperlinks make\ncertain elements of ripgrep's output, such as file paths, clickable. This\ngenerally only works in terminal emulators that support OSC-8 hyperlinks. For\nexample, the format \\fBfile://{host}{path}\\fP will emit an RFC 8089 hyperlink.\nTo see the format that ripgrep is using, pass the \\flag{debug} flag.\n.sp\nAlternatively, a format string may correspond to one of the following aliases:\n\"#,\n );\n\n let mut aliases = grep::printer::hyperlink_aliases();\n aliases.sort_by_key(|alias| {\n alias.display_priority().unwrap_or(i16::MAX)\n });\n for (i, alias) in aliases.iter().enumerate() {\n doc.push_str(r\"\\fB\");\n doc.push_str(alias.name());\n doc.push_str(r\"\\fP\");\n doc.push_str(if i < aliases.len() - 1 { \", \" } else { \".\" });\n }\n doc.push_str(\n r#\"\nThe alias will be replaced with a format string that is intended to work for\nthe corresponding application.\n.sp\nThe following variables are available in the format string:\n.sp\n.TP 12\n\\fB{path}\\fP\nRequired. This is replaced with a path to a matching file. The path is\nguaranteed to be absolute and percent encoded such that it is valid to put into\na URI. Note that a path is guaranteed to start with a /.\n.TP 12\n\\fB{host}\\fP\nOptional. This is replaced with your system's hostname. On Unix, this\ncorresponds to calling \\fBgethostname\\fP. On Windows, this corresponds to\ncalling \\fBGetComputerNameExW\\fP to fetch the system's \"physical DNS hostname.\"\nAlternatively, if \\flag{hostname-bin} was provided, then the hostname returned\nfrom the output of that program will be returned. If no hostname could be\nfound, then this variable is replaced with the empty string.\n.TP 12\n\\fB{line}\\fP\nOptional. If appropriate, this is replaced with the line number of a match. If\nno line number is available (for example, if \\fB\\-\\-no\\-line\\-number\\fP was\ngiven), then it is automatically replaced with the value 1.\n.TP 12\n\\fB{column}\\fP\nOptional, but requires the presence of \\fB{line}\\fP. If appropriate, this is\nreplaced with the column number of a match. If no column number is available\n(for example, if \\fB\\-\\-no\\-column\\fP was given), then it is automatically\nreplaced with the value 1.\n.TP 12\n\\fB{wslprefix}\\fP\nOptional. This is a special value that is set to\n\\fBwsl$/\\fP\\fIWSL_DISTRO_NAME\\fP, where \\fIWSL_DISTRO_NAME\\fP corresponds to\nthe value of the equivalent environment variable. If the system is not Unix\nor if the \\fIWSL_DISTRO_NAME\\fP environment variable is not set, then this is\nreplaced with the empty string.\n.PP\nA format string may be empty. An empty format string is equivalent to the\n\\fBnone\\fP alias. In this case, hyperlinks will be disabled.\n.sp\nAt present, ripgrep does not enable hyperlinks by default. Users must opt into\nthem. If you aren't sure what format to use, try \\fBdefault\\fP.\n.sp\nLike colors, when ripgrep detects that stdout is not connected to a tty, then\nhyperlinks are automatically disabled, regardless of the value of this flag.\nUsers can pass \\fB\\-\\-color=always\\fP to forcefully emit hyperlinks.\n.sp\nNote that hyperlinks are only written when a path is also in the output\nand colors are enabled. To write hyperlinks without colors, you'll need to\nconfigure ripgrep to not colorize anything without actually disabling all ANSI\nescape codes completely:\n.sp\n.EX\n \\-\\-colors 'path:none' \\\\\n \\-\\-colors 'line:none' \\\\\n \\-\\-colors 'column:none' \\\\\n \\-\\-colors 'match:none'\n.EE\n.sp\nripgrep works this way because it treats the \\flag{color} flag as a proxy for\nwhether ANSI escape codes should be used at all. This means that environment\nvariables like \\fBNO_COLOR=1\\fP and \\fBTERM=dumb\\fP not only disable colors,\nbut hyperlinks as well. Similarly, colors and hyperlinks are disabled when\nripgrep is not writing to a tty. (Unless one forces the issue by setting\n\\fB\\-\\-color=always\\fP.)\n.sp\nIf you're searching a file directly, for example:\n.sp\n.EX\n rg foo path/to/file\n.EE\n.sp\nthen hyperlinks will not be emitted since the path given does not appear\nin the output. To make the path appear, and thus also a hyperlink, use the\n\\flag{with-filename} flag.\n.sp\nFor more information on hyperlinks in terminal emulators, see:\nhttps://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda\n\"#,\n );\n doc\n });\n &DOC\n }\n\n fn doc_choices(&self) -> &'static [&'static str] {\n static CHOICES: LazyLock> = LazyLock::new(|| {\n let mut aliases = grep::printer::hyperlink_aliases();\n aliases.sort_by_key(|alias| {\n alias.display_priority().unwrap_or(i16::MAX)\n });\n aliases.iter().map(|alias| alias.name().to_string()).collect()\n });\n static BORROWED: LazyLock> =\n LazyLock::new(|| CHOICES.iter().map(|name| &**name).collect());\n &*BORROWED\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let v = v.unwrap_value();\n let string = convert::str(&v)?;\n let format = string.parse().context(\"invalid hyperlink format\")?;\n args.hyperlink_format = format;\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_hyperlink_format() {\n let parseformat = |format: &str| {\n format.parse::().unwrap()\n };\n\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(parseformat(\"none\"), args.hyperlink_format);\n\n let args = parse_low_raw([\"--hyperlink-format\", \"default\"]).unwrap();\n #[cfg(windows)]\n assert_eq!(parseformat(\"file://{path}\"), args.hyperlink_format);\n #[cfg(not(windows))]\n assert_eq!(parseformat(\"file://{host}{path}\"), args.hyperlink_format);\n\n let args = parse_low_raw([\"--hyperlink-format\", \"file\"]).unwrap();\n assert_eq!(parseformat(\"file://{host}{path}\"), args.hyperlink_format);\n\n let args = parse_low_raw([\n \"--hyperlink-format\",\n \"file\",\n \"--hyperlink-format=grep+\",\n ])\n .unwrap();\n assert_eq!(parseformat(\"grep+://{path}:{line}\"), args.hyperlink_format);\n\n let args =\n parse_low_raw([\"--hyperlink-format\", \"file://{host}{path}#{line}\"])\n .unwrap();\n assert_eq!(\n parseformat(\"file://{host}{path}#{line}\"),\n args.hyperlink_format\n );\n\n let result = parse_low_raw([\"--hyperlink-format\", \"file://heythere\"]);\n assert!(result.is_err(), \"{result:?}\");\n}\n\n/// --iglob\n#[derive(Debug)]\nstruct IGlob;\n\nimpl Flag for IGlob {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"iglob\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"GLOB\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Include/exclude paths case insensitively.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nInclude or exclude files and directories for searching that match the given\nglob. This always overrides any other ignore logic. Multiple glob flags may\nbe used. Globbing rules match \\fB.gitignore\\fP globs. Precede a glob with a\n\\fB!\\fP to exclude it. If multiple globs match a file or directory, the glob\ngiven later in the command line takes precedence. Globs used via this flag are\nmatched case insensitively.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let glob = convert::string(v.unwrap_value())?;\n args.iglobs.push(glob);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_iglob() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(Vec::::new(), args.iglobs);\n\n let args = parse_low_raw([\"--iglob\", \"foo\"]).unwrap();\n assert_eq!(vec![\"foo\".to_string()], args.iglobs);\n\n let args = parse_low_raw([\"--iglob=foo\"]).unwrap();\n assert_eq!(vec![\"foo\".to_string()], args.iglobs);\n\n let args = parse_low_raw([\"--iglob\", \"-foo\"]).unwrap();\n assert_eq!(vec![\"-foo\".to_string()], args.iglobs);\n\n let args = parse_low_raw([\"--iglob=-foo\"]).unwrap();\n assert_eq!(vec![\"-foo\".to_string()], args.iglobs);\n}\n\n/// -i/--ignore-case\n#[derive(Debug)]\nstruct IgnoreCase;\n\nimpl Flag for IgnoreCase {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'i')\n }\n fn name_long(&self) -> &'static str {\n \"ignore-case\"\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"Case insensitive search.\"\n }\n fn doc_long(&self) -> &'static str {\n r#\"\nWhen this flag is provided, all patterns will be searched case insensitively.\nThe case insensitivity rules used by ripgrep's default regex engine conform to\nUnicode's \"simple\" case folding rules.\n.sp\nThis is a global option that applies to all patterns given to ripgrep.\nIndividual patterns can still be matched case sensitively by using\ninline regex flags. For example, \\fB(?\\-i)abc\\fP will match \\fBabc\\fP\ncase sensitively even when this flag is used.\n.sp\nThis flag overrides \\flag{case-sensitive} and \\flag{smart-case}.\n\"#\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"flag has no negation\");\n args.case = CaseMode::Insensitive;\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_ignore_case() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(CaseMode::Sensitive, args.case);\n\n let args = parse_low_raw([\"--ignore-case\"]).unwrap();\n assert_eq!(CaseMode::Insensitive, args.case);\n\n let args = parse_low_raw([\"-i\"]).unwrap();\n assert_eq!(CaseMode::Insensitive, args.case);\n\n let args = parse_low_raw([\"-i\", \"-s\"]).unwrap();\n assert_eq!(CaseMode::Sensitive, args.case);\n\n let args = parse_low_raw([\"-s\", \"-i\"]).unwrap();\n assert_eq!(CaseMode::Insensitive, args.case);\n}\n\n/// --ignore-file\n#[derive(Debug)]\nstruct IgnoreFile;\n\nimpl Flag for IgnoreFile {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"ignore-file\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"PATH\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Specify additional ignore files.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nSpecifies a path to one or more \\fBgitignore\\fP formatted rules files.\nThese patterns are applied after the patterns found in \\fB.gitignore\\fP,\n\\fB.rgignore\\fP and \\fB.ignore\\fP are applied and are matched relative to the\ncurrent working directory. That is, files specified via this flag have lower\nprecedence than files automatically found in the directory tree. Multiple\nadditional ignore files can be specified by using this flag repeatedly. When\nspecifying multiple ignore files, earlier files have lower precedence than\nlater files.\n.sp\nIf you are looking for a way to include or exclude files and directories\ndirectly on the command line, then use \\flag{glob} instead.\n\"\n }\n fn completion_type(&self) -> CompletionType {\n CompletionType::Filename\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let path = PathBuf::from(v.unwrap_value());\n args.ignore_file.push(path);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_ignore_file() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(Vec::::new(), args.ignore_file);\n\n let args = parse_low_raw([\"--ignore-file\", \"foo\"]).unwrap();\n assert_eq!(vec![PathBuf::from(\"foo\")], args.ignore_file);\n\n let args = parse_low_raw([\"--ignore-file\", \"foo\", \"--ignore-file\", \"bar\"])\n .unwrap();\n assert_eq!(\n vec![PathBuf::from(\"foo\"), PathBuf::from(\"bar\")],\n args.ignore_file\n );\n}\n\n/// --ignore-file-case-insensitive\n#[derive(Debug)]\nstruct IgnoreFileCaseInsensitive;\n\nimpl Flag for IgnoreFileCaseInsensitive {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"ignore-file-case-insensitive\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-ignore-file-case-insensitive\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Process ignore files case insensitively.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nProcess ignore files (\\fB.gitignore\\fP, \\fB.ignore\\fP, etc.) case\ninsensitively. Note that this comes with a performance penalty and is most\nuseful on case insensitive file systems (such as Windows).\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.ignore_file_case_insensitive = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_ignore_file_case_insensitive() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.ignore_file_case_insensitive);\n\n let args = parse_low_raw([\"--ignore-file-case-insensitive\"]).unwrap();\n assert_eq!(true, args.ignore_file_case_insensitive);\n\n let args = parse_low_raw([\n \"--ignore-file-case-insensitive\",\n \"--no-ignore-file-case-insensitive\",\n ])\n .unwrap();\n assert_eq!(false, args.ignore_file_case_insensitive);\n\n let args = parse_low_raw([\n \"--no-ignore-file-case-insensitive\",\n \"--ignore-file-case-insensitive\",\n ])\n .unwrap();\n assert_eq!(true, args.ignore_file_case_insensitive);\n}\n\n/// --include-zero\n#[derive(Debug)]\nstruct IncludeZero;\n\nimpl Flag for IncludeZero {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"include-zero\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-include-zero\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Include zero matches in summary output.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhen used with \\flag{count} or \\flag{count-matches}, this causes ripgrep to\nprint the number of matches for each file even if there were zero matches. This\nis disabled by default but can be enabled to make ripgrep behave more like\ngrep.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.include_zero = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_include_zero() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.include_zero);\n\n let args = parse_low_raw([\"--include-zero\"]).unwrap();\n assert_eq!(true, args.include_zero);\n\n let args = parse_low_raw([\"--include-zero\", \"--no-include-zero\"]).unwrap();\n assert_eq!(false, args.include_zero);\n}\n\n/// -X/--index\n#[derive(Debug)]\nstruct Index;\n\nimpl Flag for Index {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'X')\n }\n fn name_long(&self) -> &'static str {\n \"index\"\n }\n fn doc_category(&self) -> Category {\n Category::Indexing\n }\n fn doc_short(&self) -> &'static str {\n r\"Use a search index when one is available.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nEnable searching with an index. Without this flag, ripgrep never uses an\nindex.\n.sp\nripgrep looks for an index in the following order. The first step that finds\none or more indexes wins:\n.sp\n.IP 1. 4\nWhen path operands are given on the command line, each operand is interpreted\nas an index directory and every index is searched in command line order. An\noperand that is not a valid index is an error.\n.sp\n.IP 2. 4\nThe index named by the \\fBRIPGREP_INDEX_PATH\\fP environment variable.\n.sp\n.IP 3. 4\nA valid index in a \\fB.ripgrep\\fP directory in the current working directory.\n.sp\n.IP 4. 4\nA valid index in a \\fB.ripgrep\\fP directory in the nearest parent of the current\nworking directory.\n.PP\nIf no index is found, ripgrep performs an ordinary search.\n.sp\nIndexed candidates are filtered by explicit glob and file-type selections,\nhidden-file and depth settings, and the maximum file size. Ignore files,\nincluding \\fB.gitignore\\fP, are not read or reapplied during an indexed search.\nOptions that require transformed contents or every file make the query\nineligible for candidate filtering and therefore trigger the fallback below.\n.sp\nThis flag may be given at most twice. When it is given once and the query\ncannot use an index, ripgrep performs an ordinary search. When it is given\ntwice and an index was found, ripgrep stops instead of performing an ordinary\nsearch if the query cannot use the index.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n check_indexing_allowed()?;\n assert!(v.unwrap_switch(), \"--index has no negation\");\n args.index = args.index.saturating_add(1);\n anyhow::ensure!(\n args.index <= 2,\n \"-X/--index may be given at most twice\"\n );\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_index() {\n if !cfg!(feature = \"unstable-index\") {\n assert!(parse_low_raw([\"-X\"]).is_err());\n return;\n }\n\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(0, args.index);\n assert_eq!(Mode::Search(SearchMode::Standard), args.mode);\n\n let args = parse_low_raw([\"-X\"]).unwrap();\n assert_eq!(1, args.index);\n assert_eq!(Mode::Search(SearchMode::Standard), args.mode);\n\n let args = parse_low_raw([\"--index\"]).unwrap();\n assert_eq!(1, args.index);\n\n let args = parse_low_raw([\"-XX\"]).unwrap();\n assert_eq!(2, args.index);\n\n let args = parse_low_raw([\"-X\", \"--index\"]).unwrap();\n assert_eq!(2, args.index);\n\n let result = parse_low_raw([\"-XXX\"]);\n assert!(result.is_err(), \"{result:?}\");\n}\n\n/// --x-crud\n#[derive(Debug)]\nstruct IndexCrud;\n\nimpl Flag for IndexCrud {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"x-crud\"\n }\n fn doc_category(&self) -> Category {\n Category::Indexing\n }\n fn doc_short(&self) -> &'static str {\n r\"Create or update a search index.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nCreate or update an index for the files and directories given on the command\nline. When no path is given, this recursively indexes the current working\ndirectory. The files added to the index are exactly those selected by\nripgrep's normal traversal and filtering options.\n.sp\nAn existing file is re-indexed only when its modification time is newer than\nthe time at which it was indexed. Use \\flag{x-force} to re-index every selected\nfile, including files on file systems with unreliable or deliberately\npreserved modification times. A previously indexed path that is no longer\naccessible is removed from the index.\n.sp\nripgrep chooses the index location in the following order:\n.sp\n.IP 1. 4\nThe path given by \\flag{x-path}.\n.sp\n.IP 2. 4\nThe path in the \\fBRIPGREP_INDEX_PATH\\fP environment variable.\n.sp\n.IP 3. 4\nA valid index in a \\fB.ripgrep\\fP directory in the current working directory.\n.sp\n.IP 4. 4\nA valid index in a \\fB.ripgrep\\fP directory in the nearest parent of the current\nworking directory.\n.sp\n.IP 5. 4\nA \\fB.ripgrep\\fP directory in the current working directory, which is created\nwhen necessary.\n.PP\nIf the final location already exists but does not contain a valid index, then\nripgrep reports an error.\n.sp\nFor example, this creates or incrementally updates an index for the current\ndirectory:\n.sp\n.EX\n rg --x-crud\n.EE\n.sp\nThis updates one path in the same index:\n.sp\n.EX\n rg --x-crud path/to/file\n.EE\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n check_indexing_allowed()?;\n assert!(v.unwrap_switch(), \"--x-crud has no negation\");\n args.mode.update(Mode::Index(IndexMode::Crud));\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_index_crud() {\n if !cfg!(feature = \"unstable-index\") {\n assert!(parse_low_raw([\"--x-crud\"]).is_err());\n return;\n }\n\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(Mode::Search(SearchMode::Standard), args.mode);\n\n let args = parse_low_raw([\"--x-crud\"]).unwrap();\n assert_eq!(Mode::Index(IndexMode::Crud), args.mode);\n\n let args = parse_low_raw([\"--files\", \"--x-crud\", \"foo\"]).unwrap();\n assert_eq!(Mode::Index(IndexMode::Crud), args.mode);\n assert_eq!(vec![std::ffi::OsString::from(\"foo\")], args.positional);\n\n let args = parse_low_raw([\"--x-crud\", \"--files\"]).unwrap();\n assert_eq!(Mode::Files, args.mode);\n}\n\n/// --x-force\n#[derive(Debug)]\nstruct IndexForce;\n\nimpl Flag for IndexForce {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"x-force\"\n }\n fn doc_category(&self) -> Category {\n Category::Indexing\n }\n fn doc_short(&self) -> &'static str {\n r\"Force selected files to be re-indexed.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhen used with \\flag{x-crud}, re-index every selected file even when its\nmodification time indicates that the index is already up to date.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n check_indexing_allowed()?;\n assert!(v.unwrap_switch(), \"--x-force has no negation\");\n args.index_force = true;\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_index_force() {\n if !cfg!(feature = \"unstable-index\") {\n assert!(parse_low_raw([\"--x-force\"]).is_err());\n return;\n }\n\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.index_force);\n\n let args = parse_low_raw([\"--x-force\"]).unwrap();\n assert_eq!(true, args.index_force);\n}\n\n/// --x-path\n#[derive(Debug)]\nstruct IndexPath;\n\nimpl Flag for IndexPath {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"x-path\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"PATH\")\n }\n fn doc_category(&self) -> Category {\n Category::Indexing\n }\n fn doc_short(&self) -> &'static str {\n r\"Set the path of the index to update.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nSet the index path used by \\flag{x-crud}. This takes precedence over\n\\fBRIPGREP_INDEX_PATH\\fP and automatic discovery of a \\fB.ripgrep\\fP directory.\n\"\n }\n fn completion_type(&self) -> CompletionType {\n CompletionType::Filename\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n check_indexing_allowed()?;\n args.index_path = Some(PathBuf::from(v.unwrap_value()));\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_index_path() {\n if !cfg!(feature = \"unstable-index\") {\n assert!(parse_low_raw([\"--x-path\"]).is_err());\n return;\n }\n\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.index_path);\n\n let args = parse_low_raw([\"--x-path\", \"foo\"]).unwrap();\n assert_eq!(Some(PathBuf::from(\"foo\")), args.index_path);\n\n let args = parse_low_raw([\"--x-path=foo\", \"--x-path\", \"bar\"]).unwrap();\n assert_eq!(Some(PathBuf::from(\"bar\")), args.index_path);\n}\n\n/// -v/--invert-match\n#[derive(Debug)]\nstruct InvertMatch;\n\nimpl Flag for InvertMatch {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'v')\n }\n fn name_long(&self) -> &'static str {\n \"invert-match\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-invert-match\")\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"Invert matching.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis flag inverts matching. That is, instead of printing lines that match,\nripgrep will print lines that don't match.\n.sp\nNote that this only inverts line-by-line matching. For example, combining this\nflag with \\flag{files-with-matches} will emit files that contain any lines\nthat do not match the patterns given. That's not the same as, for example,\n\\flag{files-without-match}, which will emit files that do not contain any\nmatching lines.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.invert_match = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_invert_match() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.invert_match);\n\n let args = parse_low_raw([\"--invert-match\"]).unwrap();\n assert_eq!(true, args.invert_match);\n\n let args = parse_low_raw([\"-v\"]).unwrap();\n assert_eq!(true, args.invert_match);\n\n let args = parse_low_raw([\"-v\", \"--no-invert-match\"]).unwrap();\n assert_eq!(false, args.invert_match);\n}\n\n/// --json\n#[derive(Debug)]\nstruct JSON;\n\nimpl Flag for JSON {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"json\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-json\")\n }\n fn doc_category(&self) -> Category {\n Category::OutputModes\n }\n fn doc_short(&self) -> &'static str {\n r\"Show search results in a JSON Lines format.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nEnable printing results in a JSON Lines format.\n.sp\nWhen this flag is provided, ripgrep will emit a sequence of messages, each\nencoded as a JSON object, where there are five different message types:\n.sp\n.TP 12\n\\fBbegin\\fP\nA message that indicates a file is being searched and contains at least one\nmatch.\n.TP 12\n\\fBend\\fP\nA message the indicates a file is done being searched. This message also\ninclude summary statistics about the search for a particular file.\n.TP 12\n\\fBmatch\\fP\nA message that indicates a match was found. This includes the text and offsets\nof the match.\n.TP 12\n\\fBcontext\\fP\nA message that indicates a contextual line was found. This includes the text of\nthe line, along with any match information if the search was inverted.\n.TP 12\n\\fBsummary\\fP\nThe final message emitted by ripgrep that contains summary statistics about the\nsearch across all files.\n.PP\nSince file paths or the contents of files are not guaranteed to be valid\nUTF-8 and JSON itself must be representable by a Unicode encoding, ripgrep\nwill emit all data elements as objects with one of two keys: \\fBtext\\fP or\n\\fBbytes\\fP. \\fBtext\\fP is a normal JSON string when the data is valid UTF-8\nwhile \\fBbytes\\fP is the base64 encoded contents of the data.\n.sp\nThe JSON Lines format is only supported for showing search results. It cannot\nbe used with other flags that emit other types of output, such as \\flag{files},\n\\flag{files-with-matches}, \\flag{files-without-match}, \\flag{count} or\n\\flag{count-matches}. ripgrep will report an error if any of the aforementioned\nflags are used in concert with \\flag{json}.\n.sp\nOther flags that control aspects of the standard output such as\n\\flag{only-matching}, \\flag{heading}, \\flag{replace}, \\flag{max-columns}, etc.,\nhave no effect when \\flag{json} is set. However, enabling JSON output will\nalways implicitly and unconditionally enable \\flag{stats}.\n.sp\nA more complete description of the JSON format used can be found here:\n\\fIhttps://docs.rs/grep-printer/*/grep_printer/struct.JSON.html\\fP.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n if v.unwrap_switch() {\n args.mode.update(Mode::Search(SearchMode::JSON));\n } else if matches!(args.mode, Mode::Search(SearchMode::JSON)) {\n // --no-json only reverts to the default mode if the mode is\n // JSON, otherwise it's a no-op.\n args.mode.update(Mode::Search(SearchMode::Standard));\n }\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_json() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(Mode::Search(SearchMode::Standard), args.mode);\n\n let args = parse_low_raw([\"--json\"]).unwrap();\n assert_eq!(Mode::Search(SearchMode::JSON), args.mode);\n\n let args = parse_low_raw([\"--json\", \"--no-json\"]).unwrap();\n assert_eq!(Mode::Search(SearchMode::Standard), args.mode);\n\n let args = parse_low_raw([\"--json\", \"--files\", \"--no-json\"]).unwrap();\n assert_eq!(Mode::Files, args.mode);\n\n let args = parse_low_raw([\"--json\", \"-l\", \"--no-json\"]).unwrap();\n assert_eq!(Mode::Search(SearchMode::FilesWithMatches), args.mode);\n}\n\n/// --line-buffered\n#[derive(Debug)]\nstruct LineBuffered;\n\nimpl Flag for LineBuffered {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"line-buffered\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-line-buffered\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Force line buffering.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhen enabled, ripgrep will always use line buffering. That is, whenever a\nmatching line is found, it will be flushed to stdout immediately. This is the\ndefault when ripgrep's stdout is connected to a tty, but otherwise, ripgrep\nwill use block buffering, which is typically faster. This flag forces ripgrep\nto use line buffering even if it would otherwise use block buffering. This is\ntypically useful in shell pipelines, for example:\n.sp\n.EX\n tail -f something.log | rg foo --line-buffered | rg bar\n.EE\n.sp\nThis overrides the \\flag{block-buffered} flag.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.buffer = if v.unwrap_switch() {\n BufferMode::Line\n } else {\n BufferMode::Auto\n };\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_line_buffered() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(BufferMode::Auto, args.buffer);\n\n let args = parse_low_raw([\"--line-buffered\"]).unwrap();\n assert_eq!(BufferMode::Line, args.buffer);\n\n let args =\n parse_low_raw([\"--line-buffered\", \"--no-line-buffered\"]).unwrap();\n assert_eq!(BufferMode::Auto, args.buffer);\n\n let args = parse_low_raw([\"--line-buffered\", \"--block-buffered\"]).unwrap();\n assert_eq!(BufferMode::Block, args.buffer);\n}\n\n/// -n/--line-number\n#[derive(Debug)]\nstruct LineNumber;\n\nimpl Flag for LineNumber {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'n')\n }\n fn name_long(&self) -> &'static str {\n \"line-number\"\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Show line numbers.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nShow line numbers (1-based).\n.sp\nThis is enabled by default when stdout is connected to a tty.\n.sp\nThis flag can be disabled by \\flag{no-line-number}.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--line-number has no automatic negation\");\n args.line_number = Some(true);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_line_number() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.line_number);\n\n let args = parse_low_raw([\"--line-number\"]).unwrap();\n assert_eq!(Some(true), args.line_number);\n\n let args = parse_low_raw([\"-n\"]).unwrap();\n assert_eq!(Some(true), args.line_number);\n\n let args = parse_low_raw([\"-n\", \"--no-line-number\"]).unwrap();\n assert_eq!(Some(false), args.line_number);\n}\n\n/// -N/--no-line-number\n#[derive(Debug)]\nstruct LineNumberNo;\n\nimpl Flag for LineNumberNo {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'N')\n }\n fn name_long(&self) -> &'static str {\n \"no-line-number\"\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Suppress line numbers.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nSuppress line numbers.\n.sp\nLine numbers are off by default when stdout is not connected to a tty.\n.sp\nLine numbers can be forcefully turned on by \\flag{line-number}.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(\n v.unwrap_switch(),\n \"--no-line-number has no automatic negation\"\n );\n args.line_number = Some(false);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_no_line_number() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.line_number);\n\n let args = parse_low_raw([\"--no-line-number\"]).unwrap();\n assert_eq!(Some(false), args.line_number);\n\n let args = parse_low_raw([\"-N\"]).unwrap();\n assert_eq!(Some(false), args.line_number);\n\n let args = parse_low_raw([\"-N\", \"--line-number\"]).unwrap();\n assert_eq!(Some(true), args.line_number);\n}\n\n/// -x/--line-regexp\n#[derive(Debug)]\nstruct LineRegexp;\n\nimpl Flag for LineRegexp {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'x')\n }\n fn name_long(&self) -> &'static str {\n \"line-regexp\"\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"Show matches surrounded by line boundaries.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhen enabled, ripgrep will only show matches surrounded by line boundaries.\nThis is equivalent to surrounding every pattern with \\fB^\\fP and \\fB$\\fP. In\nother words, this only prints lines where the entire line participates in a\nmatch.\n.sp\nThis overrides the \\flag{word-regexp} flag.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--line-regexp has no negation\");\n args.boundary = Some(BoundaryMode::Line);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_line_regexp() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.boundary);\n\n let args = parse_low_raw([\"--line-regexp\"]).unwrap();\n assert_eq!(Some(BoundaryMode::Line), args.boundary);\n\n let args = parse_low_raw([\"-x\"]).unwrap();\n assert_eq!(Some(BoundaryMode::Line), args.boundary);\n}\n\n/// -M/--max-columns\n#[derive(Debug)]\nstruct MaxColumns;\n\nimpl Flag for MaxColumns {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_short(&self) -> Option {\n Some(b'M')\n }\n fn name_long(&self) -> &'static str {\n \"max-columns\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"NUM\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Omit lines longer than this limit.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhen given, ripgrep will omit lines longer than this limit in bytes. Instead of\nprinting long lines, only the number of matches in that line is printed.\n.sp\nWhen this flag is omitted or is set to \\fB0\\fP, then it has no effect.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let max = convert::u64(&v.unwrap_value())?;\n args.max_columns = if max == 0 { None } else { Some(max) };\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_max_columns() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.max_columns);\n\n let args = parse_low_raw([\"--max-columns\", \"5\"]).unwrap();\n assert_eq!(Some(5), args.max_columns);\n\n let args = parse_low_raw([\"-M\", \"5\"]).unwrap();\n assert_eq!(Some(5), args.max_columns);\n\n let args = parse_low_raw([\"-M5\"]).unwrap();\n assert_eq!(Some(5), args.max_columns);\n\n let args = parse_low_raw([\"--max-columns\", \"5\", \"-M0\"]).unwrap();\n assert_eq!(None, args.max_columns);\n}\n\n/// --max-columns-preview\n#[derive(Debug)]\nstruct MaxColumnsPreview;\n\nimpl Flag for MaxColumnsPreview {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"max-columns-preview\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-max-columns-preview\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Show preview for lines exceeding the limit.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nPrints a preview for lines exceeding the configured max column limit.\n.sp\nWhen the \\flag{max-columns} flag is used, ripgrep will by default completely\nreplace any line that is too long with a message indicating that a matching\nline was removed. When this flag is combined with \\flag{max-columns}, a preview\nof the line (corresponding to the limit size) is shown instead, where the part\nof the line exceeding the limit is not shown.\n.sp\nIf the \\flag{max-columns} flag is not set, then this has no effect.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.max_columns_preview = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_max_columns_preview() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.max_columns_preview);\n\n let args = parse_low_raw([\"--max-columns-preview\"]).unwrap();\n assert_eq!(true, args.max_columns_preview);\n\n let args =\n parse_low_raw([\"--max-columns-preview\", \"--no-max-columns-preview\"])\n .unwrap();\n assert_eq!(false, args.max_columns_preview);\n}\n\n/// -m/--max-count\n#[derive(Debug)]\nstruct MaxCount;\n\nimpl Flag for MaxCount {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_short(&self) -> Option {\n Some(b'm')\n }\n fn name_long(&self) -> &'static str {\n \"max-count\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"NUM\")\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"Limit the number of matching lines.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nLimit the number of matching lines per file searched to \\fINUM\\fP.\n.sp\nWhen \\flag{multiline} is used, a single match that spans multiple lines is only\ncounted once for the purposes of this limit. Multiple matches in a single line\nare counted only once, as they would be in non-multiline mode.\n.sp\nWhen combined with \\flag{after-context} or \\flag{context}, it's possible for\nmore matches than the maximum to be printed if contextual lines contain a\nmatch.\n.sp\nNote that \\fB0\\fP is a legal value but not likely to be useful. When used,\nripgrep won't search anything.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.max_count = Some(convert::u64(&v.unwrap_value())?);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_max_count() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.max_count);\n\n let args = parse_low_raw([\"--max-count\", \"5\"]).unwrap();\n assert_eq!(Some(5), args.max_count);\n\n let args = parse_low_raw([\"-m\", \"5\"]).unwrap();\n assert_eq!(Some(5), args.max_count);\n\n let args = parse_low_raw([\"-m\", \"5\", \"--max-count=10\"]).unwrap();\n assert_eq!(Some(10), args.max_count);\n let args = parse_low_raw([\"-m0\"]).unwrap();\n assert_eq!(Some(0), args.max_count);\n}\n\n/// --max-depth\n#[derive(Debug)]\nstruct MaxDepth;\n\nimpl Flag for MaxDepth {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_short(&self) -> Option {\n Some(b'd')\n }\n fn name_long(&self) -> &'static str {\n \"max-depth\"\n }\n fn aliases(&self) -> &'static [&'static str] {\n &[\"maxdepth\"]\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"NUM\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Descend at most NUM directories.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis flag limits the depth of directory traversal to \\fINUM\\fP levels beyond\nthe paths given. A value of \\fB0\\fP only searches the explicitly given paths\nthemselves.\n.sp\nFor example, \\fBrg --max-depth 0 \\fP\\fIdir/\\fP is a no-op because \\fIdir/\\fP\nwill not be descended into. \\fBrg --max-depth 1 \\fP\\fIdir/\\fP will search only\nthe direct children of \\fIdir\\fP.\n.sp\nAn alternative spelling for this flag is \\fB\\-\\-maxdepth\\fP.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.max_depth = Some(convert::usize(&v.unwrap_value())?);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_max_depth() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.max_depth);\n\n let args = parse_low_raw([\"--max-depth\", \"5\"]).unwrap();\n assert_eq!(Some(5), args.max_depth);\n\n let args = parse_low_raw([\"-d\", \"5\"]).unwrap();\n assert_eq!(Some(5), args.max_depth);\n\n let args = parse_low_raw([\"--max-depth\", \"5\", \"--max-depth=10\"]).unwrap();\n assert_eq!(Some(10), args.max_depth);\n\n let args = parse_low_raw([\"--max-depth\", \"0\"]).unwrap();\n assert_eq!(Some(0), args.max_depth);\n\n let args = parse_low_raw([\"--maxdepth\", \"5\"]).unwrap();\n assert_eq!(Some(5), args.max_depth);\n}\n\n/// --max-filesize\n#[derive(Debug)]\nstruct MaxFilesize;\n\nimpl Flag for MaxFilesize {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"max-filesize\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"NUM+SUFFIX?\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Ignore files larger than NUM in size.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nIgnore files larger than \\fINUM\\fP in size. This does not apply to directories.\n.sp\nThe input format accepts suffixes of \\fBK\\fP, \\fBM\\fP or \\fBG\\fP which\ncorrespond to kilobytes, megabytes and gigabytes, respectively. If no suffix is\nprovided the input is treated as bytes.\n.sp\nExamples: \\fB\\-\\-max-filesize 50K\\fP or \\fB\\-\\-max\\-filesize 80M\\fP.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let v = v.unwrap_value();\n args.max_filesize = Some(convert::human_readable_u64(&v)?);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_max_filesize() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.max_filesize);\n\n let args = parse_low_raw([\"--max-filesize\", \"1024\"]).unwrap();\n assert_eq!(Some(1024), args.max_filesize);\n\n let args = parse_low_raw([\"--max-filesize\", \"1K\"]).unwrap();\n assert_eq!(Some(1024), args.max_filesize);\n\n let args =\n parse_low_raw([\"--max-filesize\", \"1K\", \"--max-filesize=1M\"]).unwrap();\n assert_eq!(Some(1024 * 1024), args.max_filesize);\n}\n\n/// --mmap\n#[derive(Debug)]\nstruct Mmap;\n\nimpl Flag for Mmap {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"mmap\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-mmap\")\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"Search with memory maps when possible.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhen enabled, ripgrep will search using memory maps when possible. This is\nenabled by default when ripgrep thinks it will be faster.\n.sp\nMemory map searching cannot be used in all circumstances. For example, when\nsearching virtual files or streams likes \\fBstdin\\fP. In such cases, memory\nmaps will not be used even when this flag is enabled.\n.sp\nNote that ripgrep may abort unexpectedly when memory maps are used if it\nsearches a file that is simultaneously truncated. Users can opt out of this\npossibility by disabling memory maps.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.mmap = if v.unwrap_switch() {\n MmapMode::AlwaysTryMmap\n } else {\n MmapMode::Never\n };\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_mmap() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(MmapMode::Auto, args.mmap);\n\n let args = parse_low_raw([\"--mmap\"]).unwrap();\n assert_eq!(MmapMode::AlwaysTryMmap, args.mmap);\n\n let args = parse_low_raw([\"--no-mmap\"]).unwrap();\n assert_eq!(MmapMode::Never, args.mmap);\n\n let args = parse_low_raw([\"--mmap\", \"--no-mmap\"]).unwrap();\n assert_eq!(MmapMode::Never, args.mmap);\n\n let args = parse_low_raw([\"--no-mmap\", \"--mmap\"]).unwrap();\n assert_eq!(MmapMode::AlwaysTryMmap, args.mmap);\n}\n\n/// -U/--multiline\n#[derive(Debug)]\nstruct Multiline;\n\nimpl Flag for Multiline {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'U')\n }\n fn name_long(&self) -> &'static str {\n \"multiline\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-multiline\")\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"Enable searching across multiple lines.\"\n }\n fn doc_long(&self) -> &'static str {\n r#\"\nThis flag enables searching across multiple lines.\n.sp\nWhen multiline mode is enabled, ripgrep will lift the restriction that a\nmatch cannot include a line terminator. For example, when multiline mode\nis not enabled (the default), then the regex \\fB\\\\p{any}\\fP will match any\nUnicode codepoint other than \\fB\\\\n\\fP. Similarly, the regex \\fB\\\\n\\fP is\nexplicitly forbidden, and if you try to use it, ripgrep will return an error.\nHowever, when multiline mode is enabled, \\fB\\\\p{any}\\fP will match any Unicode\ncodepoint, including \\fB\\\\n\\fP, and regexes like \\fB\\\\n\\fP are permitted.\n.sp\nAn important caveat is that multiline mode does not change the match semantics\nof \\fB.\\fP. Namely, in most regex matchers, a \\fB.\\fP will by default match any\ncharacter other than \\fB\\\\n\\fP, and this is true in ripgrep as well. In order\nto make \\fB.\\fP match \\fB\\\\n\\fP, you must enable the \"dot all\" flag inside the\nregex. For example, both \\fB(?s).\\fP and \\fB(?s:.)\\fP have the same semantics,\nwhere \\fB.\\fP will match any character, including \\fB\\\\n\\fP. Alternatively, the\n\\flag{multiline-dotall} flag may be passed to make the \"dot all\" behavior the\ndefault. This flag only applies when multiline search is enabled.\n.sp\nThere is no limit on the number of the lines that a single match can span.\n.sp\n\\fBWARNING\\fP: Because of how the underlying regex engine works, multiline\nsearches may be slower than normal line-oriented searches, and they may also\nuse more memory. In particular, when multiline mode is enabled, ripgrep\nrequires that each file it searches is laid out contiguously in memory (either\nby reading it onto the heap or by memory-mapping it). Things that cannot be\nmemory-mapped (such as \\fBstdin\\fP) will be consumed until EOF before searching\ncan begin. In general, ripgrep will only do these things when necessary.\nSpecifically, if the \\flag{multiline} flag is provided but the regex does\nnot contain patterns that would match \\fB\\\\n\\fP characters, then ripgrep\nwill automatically avoid reading each file into memory before searching it.\nNevertheless, if you only care about matches spanning at most one line, then it\nis always better to disable multiline mode.\n.sp\nThis overrides the \\flag{stop-on-nonmatch} flag.\n\"#\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.multiline = v.unwrap_switch();\n if args.multiline {\n args.stop_on_nonmatch = false;\n }\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_multiline() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.multiline);\n\n let args = parse_low_raw([\"--multiline\"]).unwrap();\n assert_eq!(true, args.multiline);\n\n let args = parse_low_raw([\"-U\"]).unwrap();\n assert_eq!(true, args.multiline);\n\n let args = parse_low_raw([\"-U\", \"--no-multiline\"]).unwrap();\n assert_eq!(false, args.multiline);\n}\n\n/// --multiline-dotall\n#[derive(Debug)]\nstruct MultilineDotall;\n\nimpl Flag for MultilineDotall {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"multiline-dotall\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-multiline-dotall\")\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"Make '.' match line terminators.\"\n }\n fn doc_long(&self) -> &'static str {\n r#\"\nThis flag enables \"dot all\" mode in all regex patterns. This causes \\fB.\\fP to\nmatch line terminators when multiline searching is enabled. This flag has no\neffect if multiline searching isn't enabled with the \\flag{multiline} flag.\n.sp\nNormally, a \\fB.\\fP will match any character except line terminators. While\nthis behavior typically isn't relevant for line-oriented matching (since\nmatches can span at most one line), this can be useful when searching with the\n\\flag{multiline} flag. By default, multiline mode runs without \"dot all\" mode\nenabled.\n.sp\nThis flag is generally intended to be used in an alias or your ripgrep config\nfile if you prefer \"dot all\" semantics by default. Note that regardless of\nwhether this flag is used, \"dot all\" semantics can still be controlled via\ninline flags in the regex pattern itself, e.g., \\fB(?s:.)\\fP always enables\n\"dot all\" whereas \\fB(?-s:.)\\fP always disables \"dot all\". Moreover, you\ncan use character classes like \\fB\\\\p{any}\\fP to match any Unicode codepoint\nregardless of whether \"dot all\" mode is enabled or not.\n\"#\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.multiline_dotall = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_multiline_dotall() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.multiline_dotall);\n\n let args = parse_low_raw([\"--multiline-dotall\"]).unwrap();\n assert_eq!(true, args.multiline_dotall);\n\n let args = parse_low_raw([\"--multiline-dotall\", \"--no-multiline-dotall\"])\n .unwrap();\n assert_eq!(false, args.multiline_dotall);\n}\n\n/// --no-config\n#[derive(Debug)]\nstruct NoConfig;\n\nimpl Flag for NoConfig {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"no-config\"\n }\n fn doc_category(&self) -> Category {\n Category::OtherBehaviors\n }\n fn doc_short(&self) -> &'static str {\n r\"Never read configuration files.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhen set, ripgrep will never read configuration files. When this flag is\npresent, ripgrep will not respect the \\fBRIPGREP_CONFIG_PATH\\fP environment\nvariable.\n.sp\nIf ripgrep ever grows a feature to automatically read configuration files in\npre-defined locations, then this flag will also disable that behavior as well.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--no-config has no negation\");\n args.no_config = true;\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_no_config() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.no_config);\n\n let args = parse_low_raw([\"--no-config\"]).unwrap();\n assert_eq!(true, args.no_config);\n}\n\n/// --no-ignore\n#[derive(Debug)]\nstruct NoIgnore;\n\nimpl Flag for NoIgnore {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"no-ignore\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"ignore\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Don't use ignore files.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhen set, ignore files such as \\fB.gitignore\\fP, \\fB.ignore\\fP and\n\\fB.rgignore\\fP will not be respected. This implies \\flag{no-ignore-dot},\n\\flag{no-ignore-exclude}, \\flag{no-ignore-global}, \\flag{no-ignore-parent} and\n\\flag{no-ignore-vcs}.\n.sp\nThis does not imply \\flag{no-ignore-files}, since \\flag{ignore-file} is\nspecified explicitly as a command line argument.\n.sp\nWhen given only once, the \\flag{unrestricted} flag is identical in\nbehavior to this flag and can be considered an alias. However, subsequent\n\\flag{unrestricted} flags have additional effects.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let yes = v.unwrap_switch();\n args.no_ignore_dot = yes;\n args.no_ignore_exclude = yes;\n args.no_ignore_global = yes;\n args.no_ignore_parent = yes;\n args.no_ignore_vcs = yes;\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_no_ignore() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.no_ignore_dot);\n assert_eq!(false, args.no_ignore_exclude);\n assert_eq!(false, args.no_ignore_global);\n assert_eq!(false, args.no_ignore_parent);\n assert_eq!(false, args.no_ignore_vcs);\n\n let args = parse_low_raw([\"--no-ignore\"]).unwrap();\n assert_eq!(true, args.no_ignore_dot);\n assert_eq!(true, args.no_ignore_exclude);\n assert_eq!(true, args.no_ignore_global);\n assert_eq!(true, args.no_ignore_parent);\n assert_eq!(true, args.no_ignore_vcs);\n\n let args = parse_low_raw([\"--no-ignore\", \"--ignore\"]).unwrap();\n assert_eq!(false, args.no_ignore_dot);\n assert_eq!(false, args.no_ignore_exclude);\n assert_eq!(false, args.no_ignore_global);\n assert_eq!(false, args.no_ignore_parent);\n assert_eq!(false, args.no_ignore_vcs);\n}\n\n/// --no-ignore-dot\n#[derive(Debug)]\nstruct NoIgnoreDot;\n\nimpl Flag for NoIgnoreDot {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"no-ignore-dot\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"ignore-dot\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Don't use .ignore or .rgignore files.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nDon't respect filter rules from \\fB.ignore\\fP or \\fB.rgignore\\fP files.\n.sp\nThis does not impact whether ripgrep will ignore files and directories whose\nnames begin with a dot. For that, see the \\flag{hidden} flag. This flag also\ndoes not impact whether filter rules from \\fB.gitignore\\fP files are respected.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.no_ignore_dot = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_no_ignore_dot() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.no_ignore_dot);\n\n let args = parse_low_raw([\"--no-ignore-dot\"]).unwrap();\n assert_eq!(true, args.no_ignore_dot);\n\n let args = parse_low_raw([\"--no-ignore-dot\", \"--ignore-dot\"]).unwrap();\n assert_eq!(false, args.no_ignore_dot);\n}\n\n/// --no-ignore-exclude\n#[derive(Debug)]\nstruct NoIgnoreExclude;\n\nimpl Flag for NoIgnoreExclude {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"no-ignore-exclude\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"ignore-exclude\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Don't use local exclusion files.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nDon't respect filter rules from files that are manually configured for the repository.\nFor example, this includes \\fBgit\\fP's \\fB.git/info/exclude\\fP.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.no_ignore_exclude = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_no_ignore_exclude() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.no_ignore_exclude);\n\n let args = parse_low_raw([\"--no-ignore-exclude\"]).unwrap();\n assert_eq!(true, args.no_ignore_exclude);\n\n let args =\n parse_low_raw([\"--no-ignore-exclude\", \"--ignore-exclude\"]).unwrap();\n assert_eq!(false, args.no_ignore_exclude);\n}\n\n/// --no-ignore-files\n#[derive(Debug)]\nstruct NoIgnoreFiles;\n\nimpl Flag for NoIgnoreFiles {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"no-ignore-files\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"ignore-files\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Don't use --ignore-file arguments.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhen set, any \\flag{ignore-file} flags, even ones that come after this flag,\nare ignored.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.no_ignore_files = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_no_ignore_files() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.no_ignore_files);\n\n let args = parse_low_raw([\"--no-ignore-files\"]).unwrap();\n assert_eq!(true, args.no_ignore_files);\n\n let args = parse_low_raw([\"--no-ignore-files\", \"--ignore-files\"]).unwrap();\n assert_eq!(false, args.no_ignore_files);\n}\n\n/// --no-ignore-global\n#[derive(Debug)]\nstruct NoIgnoreGlobal;\n\nimpl Flag for NoIgnoreGlobal {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"no-ignore-global\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"ignore-global\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Don't use global ignore files.\"\n }\n fn doc_long(&self) -> &'static str {\n r#\"\nDon't respect filter rules from ignore files that come from \"global\" sources\nsuch as \\fBgit\\fP's \\fBcore.excludesFile\\fP configuration option (which\ndefaults to \\fB$HOME/.config/git/ignore\\fP).\n\"#\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.no_ignore_global = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_no_ignore_global() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.no_ignore_global);\n\n let args = parse_low_raw([\"--no-ignore-global\"]).unwrap();\n assert_eq!(true, args.no_ignore_global);\n\n let args =\n parse_low_raw([\"--no-ignore-global\", \"--ignore-global\"]).unwrap();\n assert_eq!(false, args.no_ignore_global);\n}\n\n/// --no-ignore-messages\n#[derive(Debug)]\nstruct NoIgnoreMessages;\n\nimpl Flag for NoIgnoreMessages {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"no-ignore-messages\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"ignore-messages\")\n }\n fn doc_category(&self) -> Category {\n Category::Logging\n }\n fn doc_short(&self) -> &'static str {\n r\"Suppress gitignore parse error messages.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhen this flag is enabled, all error messages related to parsing ignore files\nare suppressed. By default, error messages are printed to stderr. In cases\nwhere these errors are expected, this flag can be used to avoid seeing the\nnoise produced by the messages.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.no_ignore_messages = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_no_ignore_messages() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.no_ignore_messages);\n\n let args = parse_low_raw([\"--no-ignore-messages\"]).unwrap();\n assert_eq!(true, args.no_ignore_messages);\n\n let args =\n parse_low_raw([\"--no-ignore-messages\", \"--ignore-messages\"]).unwrap();\n assert_eq!(false, args.no_ignore_messages);\n}\n\n/// --no-ignore-parent\n#[derive(Debug)]\nstruct NoIgnoreParent;\n\nimpl Flag for NoIgnoreParent {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"no-ignore-parent\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"ignore-parent\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Don't use ignore files in parent directories.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhen this flag is set, filter rules from ignore files found in parent\ndirectories are not respected. By default, ripgrep will ascend the parent\ndirectories of the current working directory to look for any applicable ignore\nfiles that should be applied. In some cases this may not be desirable.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.no_ignore_parent = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_no_ignore_parent() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.no_ignore_parent);\n\n let args = parse_low_raw([\"--no-ignore-parent\"]).unwrap();\n assert_eq!(true, args.no_ignore_parent);\n\n let args =\n parse_low_raw([\"--no-ignore-parent\", \"--ignore-parent\"]).unwrap();\n assert_eq!(false, args.no_ignore_parent);\n}\n\n/// --no-ignore-vcs\n#[derive(Debug)]\nstruct NoIgnoreVcs;\n\nimpl Flag for NoIgnoreVcs {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"no-ignore-vcs\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"ignore-vcs\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Don't use ignore files from source control.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhen given, filter rules from source control ignore files (e.g.,\n\\fB.gitignore\\fP) are not respected. By default, ripgrep respects \\fBgit\\fP's\nignore rules for automatic filtering. In some cases, it may not be desirable\nto respect the source control's ignore rules and instead only respect rules in\n\\fB.ignore\\fP or \\fB.rgignore\\fP.\n.sp\nNote that this flag does not directly affect the filtering of source control\nfiles or folders that start with a dot (\\fB.\\fP), like \\fB.git\\fP. These are\naffected by \\flag{hidden} and its related flags instead.\n.sp\nThis flag implies \\flag{no-ignore-parent} for source control ignore files as\nwell.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.no_ignore_vcs = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_no_ignore_vcs() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.no_ignore_vcs);\n\n let args = parse_low_raw([\"--no-ignore-vcs\"]).unwrap();\n assert_eq!(true, args.no_ignore_vcs);\n\n let args = parse_low_raw([\"--no-ignore-vcs\", \"--ignore-vcs\"]).unwrap();\n assert_eq!(false, args.no_ignore_vcs);\n}\n\n/// --no-messages\n#[derive(Debug)]\nstruct NoMessages;\n\nimpl Flag for NoMessages {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"no-messages\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"messages\")\n }\n fn doc_category(&self) -> Category {\n Category::Logging\n }\n fn doc_short(&self) -> &'static str {\n r\"Suppress some error messages.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis flag suppresses some error messages. Specifically, messages related to\nthe failed opening and reading of files. Error messages related to the syntax\nof the pattern are still shown.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.no_messages = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_no_messages() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.no_messages);\n\n let args = parse_low_raw([\"--no-messages\"]).unwrap();\n assert_eq!(true, args.no_messages);\n\n let args = parse_low_raw([\"--no-messages\", \"--messages\"]).unwrap();\n assert_eq!(false, args.no_messages);\n}\n\n/// --no-pcre2-unicode\n#[derive(Debug)]\nstruct NoPcre2Unicode;\n\nimpl Flag for NoPcre2Unicode {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"no-pcre2-unicode\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"pcre2-unicode\")\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"(DEPRECATED) Disable Unicode mode for PCRE2.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nDEPRECATED. Use \\flag{no-unicode} instead.\n.sp\nNote that Unicode mode is enabled by default.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.no_unicode = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_no_pcre2_unicode() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.no_unicode);\n\n let args = parse_low_raw([\"--no-pcre2-unicode\"]).unwrap();\n assert_eq!(true, args.no_unicode);\n\n let args =\n parse_low_raw([\"--no-pcre2-unicode\", \"--pcre2-unicode\"]).unwrap();\n assert_eq!(false, args.no_unicode);\n}\n\n/// --no-require-git\n#[derive(Debug)]\nstruct NoRequireGit;\n\nimpl Flag for NoRequireGit {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"no-require-git\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"require-git\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Use .gitignore outside of git repositories.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhen this flag is given, source control ignore files such as \\fB.gitignore\\fP\nare respected even if no \\fBgit\\fP repository is present.\n.sp\nBy default, ripgrep will only respect filter rules from source control ignore\nfiles when ripgrep detects that the search is executed inside a source control\nrepository. For example, when a \\fB.git\\fP directory is observed.\n.sp\nThis flag relaxes the default restriction. For example, it might be useful when\nthe contents of a \\fBgit\\fP repository are stored or copied somewhere, but\nwhere the repository state is absent.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.no_require_git = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_no_require_git() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.no_require_git);\n\n let args = parse_low_raw([\"--no-require-git\"]).unwrap();\n assert_eq!(true, args.no_require_git);\n\n let args = parse_low_raw([\"--no-require-git\", \"--require-git\"]).unwrap();\n assert_eq!(false, args.no_require_git);\n}\n\n/// --no-unicode\n#[derive(Debug)]\nstruct NoUnicode;\n\nimpl Flag for NoUnicode {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"no-unicode\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"unicode\")\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"Disable Unicode mode.\"\n }\n fn doc_long(&self) -> &'static str {\n r#\"\nThis flag disables Unicode mode for all patterns given to ripgrep.\n.sp\nBy default, ripgrep will enable \"Unicode mode\" in all of its regexes. This has\na number of consequences:\n.sp\n.IP \\(bu 3n\n\\fB.\\fP will only match valid UTF-8 encoded Unicode scalar values.\n.sp\n.IP \\(bu 3n\nClasses like \\fB\\\\w\\fP, \\fB\\\\s\\fP, \\fB\\\\d\\fP are all Unicode aware and much\nbigger than their ASCII only versions.\n.sp\n.IP \\(bu 3n\nCase insensitive matching will use Unicode case folding.\n.sp\n.IP \\(bu 3n\nA large array of classes like \\fB\\\\p{Emoji}\\fP are available. (Although the\nspecific set of classes available varies based on the regex engine. In general,\nthe default regex engine has more classes available to it.)\n.sp\n.IP \\(bu 3n\nWord boundaries (\\fB\\\\b\\fP and \\fB\\\\B\\fP) use the Unicode definition of a word\ncharacter.\n.PP\nIn some cases it can be desirable to turn these things off. This flag will do\nexactly that. For example, Unicode mode can sometimes have a negative impact\non performance, especially when things like \\fB\\\\w\\fP are used frequently\n(including via bounded repetitions like \\fB\\\\w{100}\\fP) when only their ASCII\ninterpretation is needed.\n\"#\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.no_unicode = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_no_unicode() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.no_unicode);\n\n let args = parse_low_raw([\"--no-unicode\"]).unwrap();\n assert_eq!(true, args.no_unicode);\n\n let args = parse_low_raw([\"--no-unicode\", \"--unicode\"]).unwrap();\n assert_eq!(false, args.no_unicode);\n\n let args = parse_low_raw([\"--no-unicode\", \"--pcre2-unicode\"]).unwrap();\n assert_eq!(false, args.no_unicode);\n\n let args = parse_low_raw([\"--no-pcre2-unicode\", \"--unicode\"]).unwrap();\n assert_eq!(false, args.no_unicode);\n}\n\n/// -0/--null\n#[derive(Debug)]\nstruct Null;\n\nimpl Flag for Null {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'0')\n }\n fn name_long(&self) -> &'static str {\n \"null\"\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Print a NUL byte after file paths.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhenever a file path is printed, follow it with a \\fBNUL\\fP byte. This includes\nprinting file paths before matches, and when printing a list of matching files\nsuch as with \\flag{count}, \\flag{files-with-matches} and \\flag{files}. This\noption is useful for use with \\fBxargs\\fP.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--null has no negation\");\n args.null = true;\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_null() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.null);\n\n let args = parse_low_raw([\"--null\"]).unwrap();\n assert_eq!(true, args.null);\n\n let args = parse_low_raw([\"-0\"]).unwrap();\n assert_eq!(true, args.null);\n}\n\n/// --null-data\n#[derive(Debug)]\nstruct NullData;\n\nimpl Flag for NullData {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"null-data\"\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"Use NUL as a line terminator.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nEnabling this flag causes ripgrep to use \\fBNUL\\fP as a line terminator instead\nof the default of \\fP\\\\n\\fP.\n.sp\nThis is useful when searching large binary files that would otherwise have\nvery long lines if \\fB\\\\n\\fP were used as the line terminator. In particular,\nripgrep requires that, at a minimum, each line must fit into memory. Using\n\\fBNUL\\fP instead can be a useful stopgap to keep memory requirements low and\navoid OOM (out of memory) conditions.\n.sp\nThis is also useful for processing NUL delimited data, such as that emitted\nwhen using ripgrep's \\flag{null} flag or \\fBfind\\fP's \\fB\\-\\-print0\\fP flag.\n.sp\nUsing this flag implies \\flag{text}. It also overrides \\flag{crlf}.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--null-data has no negation\");\n args.crlf = false;\n args.null_data = true;\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_null_data() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.null_data);\n\n let args = parse_low_raw([\"--null-data\"]).unwrap();\n assert_eq!(true, args.null_data);\n\n let args = parse_low_raw([\"--null-data\", \"--crlf\"]).unwrap();\n assert_eq!(false, args.null_data);\n assert_eq!(true, args.crlf);\n\n let args = parse_low_raw([\"--crlf\", \"--null-data\"]).unwrap();\n assert_eq!(true, args.null_data);\n assert_eq!(false, args.crlf);\n\n let args = parse_low_raw([\"--null-data\", \"--no-crlf\"]).unwrap();\n assert_eq!(true, args.null_data);\n assert_eq!(false, args.crlf);\n}\n\n/// --one-file-system\n#[derive(Debug)]\nstruct OneFileSystem;\n\nimpl Flag for OneFileSystem {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"one-file-system\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-one-file-system\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Skip directories on other file systems.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhen enabled, ripgrep will not cross file system boundaries relative to where\nthe search started from.\n.sp\nNote that this applies to each path argument given to ripgrep. For example, in\nthe command\n.sp\n.EX\n rg \\-\\-one\\-file\\-system /foo/bar /quux/baz\n.EE\n.sp\nripgrep will search both \\fI/foo/bar\\fP and \\fI/quux/baz\\fP even if they are\non different file systems, but will not cross a file system boundary when\ntraversing each path's directory tree.\n.sp\nThis is similar to \\fBfind\\fP's \\fB\\-xdev\\fP or \\fB\\-mount\\fP flag.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.one_file_system = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_one_file_system() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.one_file_system);\n\n let args = parse_low_raw([\"--one-file-system\"]).unwrap();\n assert_eq!(true, args.one_file_system);\n\n let args =\n parse_low_raw([\"--one-file-system\", \"--no-one-file-system\"]).unwrap();\n assert_eq!(false, args.one_file_system);\n}\n\n/// -o/--only-matching\n#[derive(Debug)]\nstruct OnlyMatching;\n\nimpl Flag for OnlyMatching {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'o')\n }\n fn name_long(&self) -> &'static str {\n \"only-matching\"\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Print only matched parts of a line.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nPrint only the matched (non-empty) parts of a matching line, with each such\npart on a separate output line.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--only-matching does not have a negation\");\n args.only_matching = true;\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_only_matching() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.only_matching);\n\n let args = parse_low_raw([\"--only-matching\"]).unwrap();\n assert_eq!(true, args.only_matching);\n\n let args = parse_low_raw([\"-o\"]).unwrap();\n assert_eq!(true, args.only_matching);\n}\n\n/// --path-separator\n#[derive(Debug)]\nstruct PathSeparator;\n\nimpl Flag for PathSeparator {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"path-separator\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"SEPARATOR\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Set the path separator for printing paths.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nSet the path separator to use when printing file paths. This defaults to your\nplatform's path separator, which is \\fB/\\fP on Unix and \\fB\\\\\\fP on Windows.\nThis flag is intended for overriding the default when the environment demands\nit (e.g., cygwin). A path separator is limited to a single byte.\n.sp\nSetting this flag to an empty string reverts it to its default behavior. That\nis, the path separator is automatically chosen based on the environment.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let s = convert::string(v.unwrap_value())?;\n let raw = Vec::unescape_bytes(&s);\n args.path_separator = if raw.is_empty() {\n None\n } else if raw.len() == 1 {\n Some(raw[0])\n } else {\n anyhow::bail!(\n \"A path separator must be exactly one byte, but \\\n the given separator is {len} bytes: {sep}\\n\\\n In some shells on Windows '/' is automatically \\\n expanded. Use '//' instead.\",\n len = raw.len(),\n sep = s,\n )\n };\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_path_separator() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.path_separator);\n\n let args = parse_low_raw([\"--path-separator\", \"/\"]).unwrap();\n assert_eq!(Some(b'/'), args.path_separator);\n\n let args = parse_low_raw([\"--path-separator\", r\"\\\"]).unwrap();\n assert_eq!(Some(b'\\\\'), args.path_separator);\n\n let args = parse_low_raw([\"--path-separator\", r\"\\x00\"]).unwrap();\n assert_eq!(Some(0), args.path_separator);\n\n let args = parse_low_raw([\"--path-separator\", r\"\\0\"]).unwrap();\n assert_eq!(Some(0), args.path_separator);\n\n let args = parse_low_raw([\"--path-separator\", \"\\x00\"]).unwrap();\n assert_eq!(Some(0), args.path_separator);\n\n let args = parse_low_raw([\"--path-separator\", \"\\0\"]).unwrap();\n assert_eq!(Some(0), args.path_separator);\n\n let args =\n parse_low_raw([\"--path-separator\", r\"\\x00\", \"--path-separator=/\"])\n .unwrap();\n assert_eq!(Some(b'/'), args.path_separator);\n\n let result = parse_low_raw([\"--path-separator\", \"foo\"]);\n assert!(result.is_err(), \"{result:?}\");\n\n let result = parse_low_raw([\"--path-separator\", r\"\\\\x00\"]);\n assert!(result.is_err(), \"{result:?}\");\n}\n\n/// --passthru\n#[derive(Debug)]\nstruct Passthru;\n\nimpl Flag for Passthru {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"passthru\"\n }\n fn aliases(&self) -> &'static [&'static str] {\n &[\"passthrough\"]\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Print both matching and non-matching lines.\"\n }\n fn doc_long(&self) -> &'static str {\n r#\"\nPrint both matching and non-matching lines.\n.sp\nAnother way to achieve a similar effect is by modifying your pattern to match\nthe empty string. For example, if you are searching using \\fBrg\\fP \\fIfoo\\fP,\nthen using \\fBrg\\fP \\fB'^|\\fP\\fIfoo\\fP\\fB'\\fP instead will emit every line in\nevery file searched, but only occurrences of \\fIfoo\\fP will be highlighted.\nThis flag enables the same behavior without needing to modify the pattern.\n.sp\nAn alternative spelling for this flag is \\fB\\-\\-passthrough\\fP.\n.sp\nThis overrides the \\flag{context}, \\flag{after-context} and\n\\flag{before-context} flags.\n\"#\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--passthru has no negation\");\n args.context = ContextMode::Passthru;\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_passthru() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(ContextMode::default(), args.context);\n\n let args = parse_low_raw([\"--passthru\"]).unwrap();\n assert_eq!(ContextMode::Passthru, args.context);\n\n let args = parse_low_raw([\"--passthrough\"]).unwrap();\n assert_eq!(ContextMode::Passthru, args.context);\n}\n\n/// -P/--pcre2\n#[derive(Debug)]\nstruct PCRE2;\n\nimpl Flag for PCRE2 {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'P')\n }\n fn name_long(&self) -> &'static str {\n \"pcre2\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-pcre2\")\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"Enable PCRE2 matching.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhen this flag is present, ripgrep will use the PCRE2 regex engine instead of\nits default regex engine.\n.sp\nThis is generally useful when you want to use features such as look-around\nor backreferences.\n.sp\nUsing this flag is the same as passing \\fB\\-\\-engine=pcre2\\fP. Users may\ninstead elect to use \\fB\\-\\-engine=auto\\fP to ask ripgrep to automatically\nselect the right regex engine based on the patterns given. This flag and the\n\\flag{engine} flag override one another.\n.sp\nNote that PCRE2 is an optional ripgrep feature. If PCRE2 wasn't included in\nyour build of ripgrep, then using this flag will result in ripgrep printing\nan error message and exiting. PCRE2 may also have worse user experience in\nsome cases, since it has fewer introspection APIs than ripgrep's default\nregex engine. For example, if you use a \\fB\\\\n\\fP in a PCRE2 regex without\nthe \\flag{multiline} flag, then ripgrep will silently fail to match anything\ninstead of reporting an error immediately (like it does with the default regex\nengine).\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.engine = if v.unwrap_switch() {\n EngineChoice::PCRE2\n } else {\n EngineChoice::Default\n };\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_pcre2() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(EngineChoice::Default, args.engine);\n\n let args = parse_low_raw([\"--pcre2\"]).unwrap();\n assert_eq!(EngineChoice::PCRE2, args.engine);\n\n let args = parse_low_raw([\"-P\"]).unwrap();\n assert_eq!(EngineChoice::PCRE2, args.engine);\n\n let args = parse_low_raw([\"-P\", \"--no-pcre2\"]).unwrap();\n assert_eq!(EngineChoice::Default, args.engine);\n\n let args = parse_low_raw([\"--engine=auto\", \"-P\", \"--no-pcre2\"]).unwrap();\n assert_eq!(EngineChoice::Default, args.engine);\n\n let args = parse_low_raw([\"-P\", \"--engine=auto\"]).unwrap();\n assert_eq!(EngineChoice::Auto, args.engine);\n}\n\n/// --pcre2-version\n#[derive(Debug)]\nstruct PCRE2Version;\n\nimpl Flag for PCRE2Version {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"pcre2-version\"\n }\n fn doc_category(&self) -> Category {\n Category::OtherBehaviors\n }\n fn doc_short(&self) -> &'static str {\n r\"Print the version of PCRE2 that ripgrep uses.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhen this flag is present, ripgrep will print the version of PCRE2 in use,\nalong with other information, and then exit. If PCRE2 is not available, then\nripgrep will print an error message and exit with an error code.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--pcre2-version has no negation\");\n args.special = Some(SpecialMode::VersionPCRE2);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_pcre2_version() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.special);\n\n let args = parse_low_raw([\"--pcre2-version\"]).unwrap();\n assert_eq!(Some(SpecialMode::VersionPCRE2), args.special);\n}\n\n/// --pre\n#[derive(Debug)]\nstruct Pre;\n\nimpl Flag for Pre {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"pre\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-pre\")\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"COMMAND\")\n }\n fn doc_category(&self) -> Category {\n Category::Input\n }\n fn doc_short(&self) -> &'static str {\n r\"Search output of COMMAND for each PATH.\"\n }\n fn doc_long(&self) -> &'static str {\n r#\"\nFor each input \\fIPATH\\fP, this flag causes ripgrep to search the standard\noutput of \\fICOMMAND\\fP \\fIPATH\\fP instead of the contents of \\fIPATH\\fP.\nThis option expects the \\fICOMMAND\\fP program to either be a path or to be\navailable in your \\fBPATH\\fP. Either an empty string \\fICOMMAND\\fP or the\n\\fB\\-\\-no\\-pre\\fP flag will disable this behavior.\n.sp\n.TP 12\n\\fBWARNING\\fP\nWhen this flag is set, ripgrep will unconditionally spawn a process for every\nfile that is searched. Therefore, this can incur an unnecessarily large\nperformance penalty if you don't otherwise need the flexibility offered by this\nflag. One possible mitigation to this is to use the \\flag{pre-glob} flag to\nlimit which files a preprocessor is run with.\n.PP\nA preprocessor is not run when ripgrep is searching stdin.\n.sp\nWhen searching over sets of files that may require one of several\npreprocessors, \\fICOMMAND\\fP should be a wrapper program which first classifies\n\\fIPATH\\fP based on magic numbers/content or based on the \\fIPATH\\fP name and\nthen dispatches to an appropriate preprocessor. Each \\fICOMMAND\\fP also has its\nstandard input connected to \\fIPATH\\fP for convenience.\n.sp\nFor example, a shell script for \\fICOMMAND\\fP might look like:\n.sp\n.EX\n case \"$1\" in\n *.pdf)\n exec pdftotext \"$1\" -\n ;;\n *)\n case $(file \"$1\") in\n *Zstandard*)\n exec pzstd -cdq\n ;;\n *)\n exec cat\n ;;\n esac\n ;;\n esac\n.EE\n.sp\nThe above script uses \\fBpdftotext\\fP to convert a PDF file to plain text. For\nall other files, the script uses the \\fBfile\\fP utility to sniff the type of\nthe file based on its contents. If it is a compressed file in the Zstandard\nformat, then \\fBpzstd\\fP is used to decompress the contents to stdout.\n.sp\nThis overrides the \\flag{search-zip} flag.\n\"#\n }\n fn completion_type(&self) -> CompletionType {\n CompletionType::Executable\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let path = match v {\n FlagValue::Value(v) => PathBuf::from(v),\n FlagValue::Switch(yes) => {\n assert!(!yes, \"there is no affirmative switch for --pre\");\n args.pre = None;\n return Ok(());\n }\n };\n args.pre = if path.as_os_str().is_empty() { None } else { Some(path) };\n if args.pre.is_some() {\n args.search_zip = false;\n }\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_pre() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.pre);\n\n let args = parse_low_raw([\"--pre\", \"foo/bar\"]).unwrap();\n assert_eq!(Some(PathBuf::from(\"foo/bar\")), args.pre);\n\n let args = parse_low_raw([\"--pre\", \"\"]).unwrap();\n assert_eq!(None, args.pre);\n\n let args = parse_low_raw([\"--pre\", \"foo/bar\", \"--pre\", \"\"]).unwrap();\n assert_eq!(None, args.pre);\n\n let args = parse_low_raw([\"--pre\", \"foo/bar\", \"--pre=\"]).unwrap();\n assert_eq!(None, args.pre);\n\n let args = parse_low_raw([\"--pre\", \"foo/bar\", \"--no-pre\"]).unwrap();\n assert_eq!(None, args.pre);\n}\n\n/// --pre-glob\n#[derive(Debug)]\nstruct PreGlob;\n\nimpl Flag for PreGlob {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"pre-glob\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"GLOB\")\n }\n fn doc_category(&self) -> Category {\n Category::Input\n }\n fn doc_short(&self) -> &'static str {\n r\"Include or exclude files from a preprocessor.\"\n }\n fn doc_long(&self) -> &'static str {\n r#\"\nThis flag works in conjunction with the \\flag{pre} flag. Namely, when one or\nmore \\flag{pre-glob} flags are given, then only files that match the given set\nof globs will be handed to the command specified by the \\flag{pre} flag. Any\nnon-matching files will be searched without using the preprocessor command.\n.sp\nThis flag is useful when searching many files with the \\flag{pre} flag.\nNamely, it provides the ability to avoid process overhead for files that\ndon't need preprocessing. For example, given the following shell script,\n\\fIpre-pdftotext\\fP:\n.sp\n.EX\n #!/bin/sh\n pdftotext \"$1\" -\n.EE\n.sp\nthen it is possible to use \\fB\\-\\-pre\\fP \\fIpre-pdftotext\\fP\n\\fB\\-\\-pre\\-glob\\fP '\\fI*.pdf\\fP' to make it so ripgrep only executes\nthe \\fIpre-pdftotext\\fP command on files with a \\fI.pdf\\fP extension.\n.sp\nMultiple \\flag{pre-glob} flags may be used. Globbing rules match\n\\fBgitignore\\fP globs. Precede a glob with a \\fB!\\fP to exclude it.\n.sp\nThis flag has no effect if the \\flag{pre} flag is not used.\n\"#\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let glob = convert::string(v.unwrap_value())?;\n args.pre_glob.push(glob);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_pre_glob() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(Vec::::new(), args.pre_glob);\n\n let args = parse_low_raw([\"--pre-glob\", \"*.pdf\"]).unwrap();\n assert_eq!(vec![\"*.pdf\".to_string()], args.pre_glob);\n\n let args =\n parse_low_raw([\"--pre-glob\", \"*.pdf\", \"--pre-glob=foo\"]).unwrap();\n assert_eq!(vec![\"*.pdf\".to_string(), \"foo\".to_string()], args.pre_glob);\n}\n\n/// -p/--pretty\n#[derive(Debug)]\nstruct Pretty;\n\nimpl Flag for Pretty {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'p')\n }\n fn name_long(&self) -> &'static str {\n \"pretty\"\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Alias for colors, headings and line numbers.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis is a convenience alias for \\fB\\-\\-color=always \\-\\-heading\n\\-\\-line\\-number\\fP. This flag is useful when you still want pretty output even\nif you're piping ripgrep to another program or file. For example: \\fBrg -p\n\\fP\\fIfoo\\fP \\fB| less -R\\fP.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--pretty has no negation\");\n args.color = ColorChoice::Always;\n args.heading = Some(true);\n args.line_number = Some(true);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_pretty() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(ColorChoice::Auto, args.color);\n assert_eq!(None, args.heading);\n assert_eq!(None, args.line_number);\n\n let args = parse_low_raw([\"--pretty\"]).unwrap();\n assert_eq!(ColorChoice::Always, args.color);\n assert_eq!(Some(true), args.heading);\n assert_eq!(Some(true), args.line_number);\n\n let args = parse_low_raw([\"-p\"]).unwrap();\n assert_eq!(ColorChoice::Always, args.color);\n assert_eq!(Some(true), args.heading);\n assert_eq!(Some(true), args.line_number);\n}\n\n/// -q/--quiet\n#[derive(Debug)]\nstruct Quiet;\n\nimpl Flag for Quiet {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'q')\n }\n fn name_long(&self) -> &'static str {\n \"quiet\"\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Do not print anything to stdout.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nDo not print anything to stdout. If a match is found in a file, then ripgrep\nwill stop searching. This is useful when ripgrep is used only for its exit code\n(which will be an error code if no matches are found).\n.sp\nWhen \\flag{files} is used, ripgrep will stop finding files after finding the\nfirst file that does not match any ignore rules.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--quiet has no negation\");\n args.quiet = true;\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_quiet() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.quiet);\n\n let args = parse_low_raw([\"--quiet\"]).unwrap();\n assert_eq!(true, args.quiet);\n\n let args = parse_low_raw([\"-q\"]).unwrap();\n assert_eq!(true, args.quiet);\n\n // flags like -l and --json cannot override -q, regardless of order\n let args = parse_low_raw([\"-q\", \"--json\"]).unwrap();\n assert_eq!(true, args.quiet);\n\n let args = parse_low_raw([\"-q\", \"--files-with-matches\"]).unwrap();\n assert_eq!(true, args.quiet);\n\n let args = parse_low_raw([\"-q\", \"--files-without-match\"]).unwrap();\n assert_eq!(true, args.quiet);\n\n let args = parse_low_raw([\"-q\", \"--count\"]).unwrap();\n assert_eq!(true, args.quiet);\n\n let args = parse_low_raw([\"-q\", \"--count-matches\"]).unwrap();\n assert_eq!(true, args.quiet);\n}\n\n/// --regex-size-limit\n#[derive(Debug)]\nstruct RegexSizeLimit;\n\nimpl Flag for RegexSizeLimit {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"regex-size-limit\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"NUM+SUFFIX?\")\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"The size limit of the compiled regex.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThe size limit of the compiled regex, where the compiled regex generally\ncorresponds to a single object in memory that can match all of the patterns\nprovided to ripgrep. The default limit is generous enough that most reasonable\npatterns (or even a small number of them) should fit.\n.sp\nThis useful to change when you explicitly want to let ripgrep spend potentially\nmuch more time and/or memory building a regex matcher.\n.sp\nThe input format accepts suffixes of \\fBK\\fP, \\fBM\\fP or \\fBG\\fP which\ncorrespond to kilobytes, megabytes and gigabytes, respectively. If no suffix is\nprovided the input is treated as bytes.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let v = v.unwrap_value();\n args.regex_size_limit = Some(convert::human_readable_usize(&v)?);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_regex_size_limit() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.regex_size_limit);\n\n #[cfg(target_pointer_width = \"64\")]\n {\n let args = parse_low_raw([\"--regex-size-limit\", \"9G\"]).unwrap();\n assert_eq!(Some(9 * (1 << 30)), args.regex_size_limit);\n\n let args = parse_low_raw([\"--regex-size-limit=9G\"]).unwrap();\n assert_eq!(Some(9 * (1 << 30)), args.regex_size_limit);\n\n let args =\n parse_low_raw([\"--regex-size-limit=9G\", \"--regex-size-limit=0\"])\n .unwrap();\n assert_eq!(Some(0), args.regex_size_limit);\n }\n\n let args = parse_low_raw([\"--regex-size-limit=0K\"]).unwrap();\n assert_eq!(Some(0), args.regex_size_limit);\n\n let args = parse_low_raw([\"--regex-size-limit=0M\"]).unwrap();\n assert_eq!(Some(0), args.regex_size_limit);\n\n let args = parse_low_raw([\"--regex-size-limit=0G\"]).unwrap();\n assert_eq!(Some(0), args.regex_size_limit);\n\n let result =\n parse_low_raw([\"--regex-size-limit\", \"9999999999999999999999\"]);\n assert!(result.is_err(), \"{result:?}\");\n\n let result = parse_low_raw([\"--regex-size-limit\", \"9999999999999999G\"]);\n assert!(result.is_err(), \"{result:?}\");\n}\n\n/// -e/--regexp\n#[derive(Debug)]\nstruct Regexp;\n\nimpl Flag for Regexp {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_short(&self) -> Option {\n Some(b'e')\n }\n fn name_long(&self) -> &'static str {\n \"regexp\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"PATTERN\")\n }\n fn doc_category(&self) -> Category {\n Category::Input\n }\n fn doc_short(&self) -> &'static str {\n r\"A pattern to search for.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nA pattern to search for. This option can be provided multiple times, where\nall patterns given are searched, in addition to any patterns provided by\n\\flag{file}. Lines matching at least one of the provided patterns are printed.\nThis flag can also be used when searching for patterns that start with a dash.\n.sp\nFor example, to search for the literal \\fB\\-foo\\fP:\n.sp\n.EX\n rg \\-e \\-foo\n.EE\n.sp\nYou can also use the special \\fB\\-\\-\\fP delimiter to indicate that no more\nflags will be provided. Namely, the following is equivalent to the above:\n.sp\n.EX\n rg \\-\\- \\-foo\n.EE\n.sp\nWhen \\flag{file} or \\flag{regexp} is used, then ripgrep treats all positional\narguments as files or directories to search.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let regexp = convert::string(v.unwrap_value())?;\n args.patterns.push(PatternSource::Regexp(regexp));\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_regexp() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(Vec::::new(), args.patterns);\n\n let args = parse_low_raw([\"--regexp\", \"foo\"]).unwrap();\n assert_eq!(vec![PatternSource::Regexp(\"foo\".to_string())], args.patterns);\n\n let args = parse_low_raw([\"--regexp=foo\"]).unwrap();\n assert_eq!(vec![PatternSource::Regexp(\"foo\".to_string())], args.patterns);\n\n let args = parse_low_raw([\"-e\", \"foo\"]).unwrap();\n assert_eq!(vec![PatternSource::Regexp(\"foo\".to_string())], args.patterns);\n\n let args = parse_low_raw([\"-efoo\"]).unwrap();\n assert_eq!(vec![PatternSource::Regexp(\"foo\".to_string())], args.patterns);\n\n let args = parse_low_raw([\"--regexp\", \"-foo\"]).unwrap();\n assert_eq!(vec![PatternSource::Regexp(\"-foo\".to_string())], args.patterns);\n\n let args = parse_low_raw([\"--regexp=-foo\"]).unwrap();\n assert_eq!(vec![PatternSource::Regexp(\"-foo\".to_string())], args.patterns);\n\n let args = parse_low_raw([\"-e\", \"-foo\"]).unwrap();\n assert_eq!(vec![PatternSource::Regexp(\"-foo\".to_string())], args.patterns);\n\n let args = parse_low_raw([\"-e-foo\"]).unwrap();\n assert_eq!(vec![PatternSource::Regexp(\"-foo\".to_string())], args.patterns);\n\n let args = parse_low_raw([\"--regexp=foo\", \"--regexp\", \"bar\"]).unwrap();\n assert_eq!(\n vec![\n PatternSource::Regexp(\"foo\".to_string()),\n PatternSource::Regexp(\"bar\".to_string())\n ],\n args.patterns\n );\n\n // While we support invalid UTF-8 arguments in general, patterns must be\n // valid UTF-8.\n #[cfg(unix)]\n {\n use std::{ffi::OsStr, os::unix::ffi::OsStrExt};\n\n let bytes = &[b'A', 0xFF, b'Z'][..];\n let result = parse_low_raw([\n OsStr::from_bytes(b\"-e\"),\n OsStr::from_bytes(bytes),\n ]);\n assert!(result.is_err(), \"{result:?}\");\n }\n\n // Check that combining -e/--regexp and -f/--file works as expected.\n let args = parse_low_raw([\"-efoo\", \"-fbar\"]).unwrap();\n assert_eq!(\n vec![\n PatternSource::Regexp(\"foo\".to_string()),\n PatternSource::File(PathBuf::from(\"bar\"))\n ],\n args.patterns\n );\n\n let args = parse_low_raw([\"-efoo\", \"-fbar\", \"-equux\"]).unwrap();\n assert_eq!(\n vec![\n PatternSource::Regexp(\"foo\".to_string()),\n PatternSource::File(PathBuf::from(\"bar\")),\n PatternSource::Regexp(\"quux\".to_string()),\n ],\n args.patterns\n );\n}\n\n/// -r/--replace\n#[derive(Debug)]\nstruct Replace;\n\nimpl Flag for Replace {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_short(&self) -> Option {\n Some(b'r')\n }\n fn name_long(&self) -> &'static str {\n \"replace\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"REPLACEMENT\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Replace matches with the given text.\"\n }\n fn doc_long(&self) -> &'static str {\n r#\"\nReplaces every match with the text given when printing results. Neither this\nflag nor any other ripgrep flag will modify your files.\n.sp\nCapture group indices (e.g., \\fB$\\fP\\fI5\\fP) and names (e.g., \\fB$\\fP\\fIfoo\\fP)\nare supported in the replacement string. Capture group indices are numbered\nbased on the position of the opening parenthesis of the group, where the\nleftmost such group is \\fB$\\fP\\fI1\\fP. The special \\fB$\\fP\\fI0\\fP group\ncorresponds to the entire match.\n.sp\nThe name of a group is formed by taking the longest string of letters, numbers\nand underscores (i.e. \\fB[_0-9A-Za-z]\\fP) after the \\fB$\\fP. For example,\n\\fB$\\fP\\fI1a\\fP will be replaced with the group named \\fI1a\\fP, not the\ngroup at index \\fI1\\fP. If the group's name contains characters that aren't\nletters, numbers or underscores, or you want to immediately follow the group\nwith another string, the name should be put inside braces. For example,\n\\fB${\\fP\\fI1\\fP\\fB}\\fP\\fIa\\fP will take the content of the group at index\n\\fI1\\fP and append \\fIa\\fP to the end of it.\n.sp\nIf an index or name does not refer to a valid capture group, it will be\nreplaced with an empty string.\n.sp\nIn shells such as Bash and zsh, you should wrap the pattern in single quotes\ninstead of double quotes. Otherwise, capture group indices will be replaced by\nexpanded shell variables which will most likely be empty.\n.sp\nTo write a literal \\fB$\\fP, use \\fB$$\\fP.\n.sp\nNote that the replacement by default replaces each match, and not the entire\nline. To replace the entire line, you should match the entire line.\n.sp\nThis flag can be used with the \\flag{only-matching} flag.\n\"#\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.replace = Some(convert::string(v.unwrap_value())?.into());\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_replace() {\n use bstr::BString;\n\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.replace);\n\n let args = parse_low_raw([\"--replace\", \"foo\"]).unwrap();\n assert_eq!(Some(BString::from(\"foo\")), args.replace);\n\n let args = parse_low_raw([\"--replace\", \"-foo\"]).unwrap();\n assert_eq!(Some(BString::from(\"-foo\")), args.replace);\n\n let args = parse_low_raw([\"-r\", \"foo\"]).unwrap();\n assert_eq!(Some(BString::from(\"foo\")), args.replace);\n\n let args = parse_low_raw([\"-r\", \"foo\", \"-rbar\"]).unwrap();\n assert_eq!(Some(BString::from(\"bar\")), args.replace);\n\n let args = parse_low_raw([\"-r\", \"foo\", \"-r\", \"\"]).unwrap();\n assert_eq!(Some(BString::from(\"\")), args.replace);\n}\n\n/// -z/--search-zip\n#[derive(Debug)]\nstruct SearchZip;\n\nimpl Flag for SearchZip {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'z')\n }\n fn name_long(&self) -> &'static str {\n \"search-zip\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-search-zip\")\n }\n fn doc_category(&self) -> Category {\n Category::Input\n }\n fn doc_short(&self) -> &'static str {\n r\"Search in compressed files.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis flag instructs ripgrep to search in compressed files. Currently gzip,\nbzip2, xz, LZ4, LZMA, Brotli and Zstd files are supported. This option expects\nthe decompression binaries (such as \\fBgzip\\fP) to be available in your\n\\fBPATH\\fP. If the required binaries are not found, then ripgrep will not\nemit an error messages by default. Use the \\flag{debug} flag to see more\ninformation.\n.sp\nNote that this flag does not make ripgrep search archive formats as directory\ntrees. It only makes ripgrep detect compressed files and then decompress them\nbefore searching their contents as it would any other file.\n.sp\nThis overrides the \\flag{pre} flag.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.search_zip = if v.unwrap_switch() {\n args.pre = None;\n true\n } else {\n false\n };\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_search_zip() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.search_zip);\n\n let args = parse_low_raw([\"--search-zip\"]).unwrap();\n assert_eq!(true, args.search_zip);\n\n let args = parse_low_raw([\"-z\"]).unwrap();\n assert_eq!(true, args.search_zip);\n\n let args = parse_low_raw([\"-z\", \"--no-search-zip\"]).unwrap();\n assert_eq!(false, args.search_zip);\n\n let args = parse_low_raw([\"--pre=foo\", \"--no-search-zip\"]).unwrap();\n assert_eq!(Some(PathBuf::from(\"foo\")), args.pre);\n assert_eq!(false, args.search_zip);\n\n let args = parse_low_raw([\"--pre=foo\", \"--search-zip\"]).unwrap();\n assert_eq!(None, args.pre);\n assert_eq!(true, args.search_zip);\n\n let args = parse_low_raw([\"--pre=foo\", \"-z\", \"--no-search-zip\"]).unwrap();\n assert_eq!(None, args.pre);\n assert_eq!(false, args.search_zip);\n}\n\n/// -S/--smart-case\n#[derive(Debug)]\nstruct SmartCase;\n\nimpl Flag for SmartCase {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'S')\n }\n fn name_long(&self) -> &'static str {\n \"smart-case\"\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"Smart case search.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis flag instructs ripgrep to searches case insensitively if the pattern is\nall lowercase. Otherwise, ripgrep will search case sensitively.\n.sp\nA pattern is considered all lowercase if both of the following rules hold:\n.sp\n.IP \\(bu 3n\nFirst, the pattern contains at least one literal character. For example,\n\\fBa\\\\w\\fP contains a literal (\\fBa\\fP) but just \\fB\\\\w\\fP does not.\n.sp\n.IP \\(bu 3n\nSecond, of the literals in the pattern, none of them are considered to be\nuppercase according to Unicode. For example, \\fBfoo\\\\pL\\fP has no uppercase\nliterals but \\fBFoo\\\\pL\\fP does.\n.PP\nThis overrides the \\flag{case-sensitive} and \\flag{ignore-case} flags.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--smart-case flag has no negation\");\n args.case = CaseMode::Smart;\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_smart_case() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(CaseMode::Sensitive, args.case);\n\n let args = parse_low_raw([\"--smart-case\"]).unwrap();\n assert_eq!(CaseMode::Smart, args.case);\n\n let args = parse_low_raw([\"-S\"]).unwrap();\n assert_eq!(CaseMode::Smart, args.case);\n\n let args = parse_low_raw([\"-S\", \"-s\"]).unwrap();\n assert_eq!(CaseMode::Sensitive, args.case);\n\n let args = parse_low_raw([\"-S\", \"-i\"]).unwrap();\n assert_eq!(CaseMode::Insensitive, args.case);\n\n let args = parse_low_raw([\"-s\", \"-S\"]).unwrap();\n assert_eq!(CaseMode::Smart, args.case);\n\n let args = parse_low_raw([\"-i\", \"-S\"]).unwrap();\n assert_eq!(CaseMode::Smart, args.case);\n}\n\n/// --sort-files\n#[derive(Debug)]\nstruct SortFiles;\n\nimpl Flag for SortFiles {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"sort-files\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-sort-files\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"(DEPRECATED) Sort results by file path.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nDEPRECATED. Use \\fB\\-\\-sort=path\\fP instead.\n.sp\nThis flag instructs ripgrep to sort search results by file path\nlexicographically in ascending order. Note that this currently disables all\nparallelism and runs search in a single thread.\n.sp\nThis flag overrides \\flag{sort} and \\flag{sortr}.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.sort = if v.unwrap_switch() {\n Some(SortMode { reverse: false, kind: SortModeKind::Path })\n } else {\n None\n };\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_sort_files() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.sort);\n\n let args = parse_low_raw([\"--sort-files\"]).unwrap();\n assert_eq!(\n Some(SortMode { reverse: false, kind: SortModeKind::Path }),\n args.sort\n );\n\n let args = parse_low_raw([\"--sort-files\", \"--no-sort-files\"]).unwrap();\n assert_eq!(None, args.sort);\n\n let args = parse_low_raw([\"--sort\", \"created\", \"--sort-files\"]).unwrap();\n assert_eq!(\n Some(SortMode { reverse: false, kind: SortModeKind::Path }),\n args.sort\n );\n\n let args = parse_low_raw([\"--sort-files\", \"--sort\", \"created\"]).unwrap();\n assert_eq!(\n Some(SortMode { reverse: false, kind: SortModeKind::Created }),\n args.sort\n );\n\n let args = parse_low_raw([\"--sortr\", \"created\", \"--sort-files\"]).unwrap();\n assert_eq!(\n Some(SortMode { reverse: false, kind: SortModeKind::Path }),\n args.sort\n );\n\n let args = parse_low_raw([\"--sort-files\", \"--sortr\", \"created\"]).unwrap();\n assert_eq!(\n Some(SortMode { reverse: true, kind: SortModeKind::Created }),\n args.sort\n );\n\n let args = parse_low_raw([\"--sort=path\", \"--no-sort-files\"]).unwrap();\n assert_eq!(None, args.sort);\n\n let args = parse_low_raw([\"--sortr=path\", \"--no-sort-files\"]).unwrap();\n assert_eq!(None, args.sort);\n}\n\n/// --sort\n#[derive(Debug)]\nstruct Sort;\n\nimpl Flag for Sort {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"sort\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"SORTBY\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Sort results in ascending order.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis flag enables sorting of results in ascending order. The possible values\nfor this flag are:\n.sp\n.TP 12\n\\fBnone\\fP\n(Default) Do not sort results. Fastest. Can be multi-threaded.\n.TP 12\n\\fBpath\\fP\nSort by file path. Always single-threaded. The order is determined by sorting\nfiles in each directory entry during traversal. This means that given the files\n\\fBa/b\\fP and \\fBa+\\fP, the latter will sort after the former even though\n\\fB+\\fP would normally sort before \\fB/\\fP.\n.TP 12\n\\fBmodified\\fP\nSort by the last modified time on a file. Always single-threaded.\n.TP 12\n\\fBaccessed\\fP\nSort by the last accessed time on a file. Always single-threaded.\n.TP 12\n\\fBcreated\\fP\nSort by the creation time on a file. Always single-threaded.\n.PP\nIf the chosen (manually or by-default) sorting criteria isn't available on your\nsystem (for example, creation time is not available on ext4 file systems), then\nripgrep will attempt to detect this, print an error and exit without searching.\n.sp\nTo sort results in reverse or descending order, use the \\flag{sortr} flag.\nAlso, this flag overrides \\flag{sortr}.\n.sp\nNote that sorting results currently always forces ripgrep to abandon\nparallelism and run in a single thread.\n\"\n }\n fn doc_choices(&self) -> &'static [&'static str] {\n &[\"none\", \"path\", \"modified\", \"accessed\", \"created\"]\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let kind = match convert::str(&v.unwrap_value())? {\n \"none\" => {\n args.sort = None;\n return Ok(());\n }\n \"path\" => SortModeKind::Path,\n \"modified\" => SortModeKind::LastModified,\n \"accessed\" => SortModeKind::LastAccessed,\n \"created\" => SortModeKind::Created,\n unk => anyhow::bail!(\"choice '{unk}' is unrecognized\"),\n };\n args.sort = Some(SortMode { reverse: false, kind });\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_sort() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.sort);\n\n let args = parse_low_raw([\"--sort\", \"path\"]).unwrap();\n assert_eq!(\n Some(SortMode { reverse: false, kind: SortModeKind::Path }),\n args.sort\n );\n\n let args = parse_low_raw([\"--sort\", \"path\", \"--sort=created\"]).unwrap();\n assert_eq!(\n Some(SortMode { reverse: false, kind: SortModeKind::Created }),\n args.sort\n );\n\n let args = parse_low_raw([\"--sort=none\"]).unwrap();\n assert_eq!(None, args.sort);\n\n let args = parse_low_raw([\"--sort\", \"path\", \"--sort=none\"]).unwrap();\n assert_eq!(None, args.sort);\n}\n\n/// --sortr\n#[derive(Debug)]\nstruct Sortr;\n\nimpl Flag for Sortr {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"sortr\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"SORTBY\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Sort results in descending order.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis flag enables sorting of results in descending order. The possible values\nfor this flag are:\n.sp\n.TP 12\n\\fBnone\\fP\n(Default) Do not sort results. Fastest. Can be multi-threaded.\n.TP 12\n\\fBpath\\fP\nSort by file path. Always single-threaded. The order is determined by sorting\nfiles in each directory entry during traversal. This means that given the files\n\\fBa/b\\fP and \\fBa+\\fP, the latter will sort before the former even though\n\\fB+\\fP would normally sort after \\fB/\\fP when doing a reverse lexicographic\nsort.\n.TP 12\n\\fBmodified\\fP\nSort by the last modified time on a file. Always single-threaded.\n.TP 12\n\\fBaccessed\\fP\nSort by the last accessed time on a file. Always single-threaded.\n.TP 12\n\\fBcreated\\fP\nSort by the creation time on a file. Always single-threaded.\n.PP\nIf the chosen (manually or by-default) sorting criteria isn't available on your\nsystem (for example, creation time is not available on ext4 file systems), then\nripgrep will attempt to detect this, print an error and exit without searching.\n.sp\nTo sort results in ascending order, use the \\flag{sort} flag. Also, this flag\noverrides \\flag{sort}.\n.sp\nNote that sorting results currently always forces ripgrep to abandon\nparallelism and run in a single thread.\n\"\n }\n fn doc_choices(&self) -> &'static [&'static str] {\n &[\"none\", \"path\", \"modified\", \"accessed\", \"created\"]\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let kind = match convert::str(&v.unwrap_value())? {\n \"none\" => {\n args.sort = None;\n return Ok(());\n }\n \"path\" => SortModeKind::Path,\n \"modified\" => SortModeKind::LastModified,\n \"accessed\" => SortModeKind::LastAccessed,\n \"created\" => SortModeKind::Created,\n unk => anyhow::bail!(\"choice '{unk}' is unrecognized\"),\n };\n args.sort = Some(SortMode { reverse: true, kind });\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_sortr() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.sort);\n\n let args = parse_low_raw([\"--sortr\", \"path\"]).unwrap();\n assert_eq!(\n Some(SortMode { reverse: true, kind: SortModeKind::Path }),\n args.sort\n );\n\n let args = parse_low_raw([\"--sortr\", \"path\", \"--sortr=created\"]).unwrap();\n assert_eq!(\n Some(SortMode { reverse: true, kind: SortModeKind::Created }),\n args.sort\n );\n\n let args = parse_low_raw([\"--sortr=none\"]).unwrap();\n assert_eq!(None, args.sort);\n\n let args = parse_low_raw([\"--sortr\", \"path\", \"--sortr=none\"]).unwrap();\n assert_eq!(None, args.sort);\n\n let args = parse_low_raw([\"--sort=path\", \"--sortr=path\"]).unwrap();\n assert_eq!(\n Some(SortMode { reverse: true, kind: SortModeKind::Path }),\n args.sort\n );\n\n let args = parse_low_raw([\"--sortr=path\", \"--sort=path\"]).unwrap();\n assert_eq!(\n Some(SortMode { reverse: false, kind: SortModeKind::Path }),\n args.sort\n );\n}\n\n/// --stats\n#[derive(Debug)]\nstruct Stats;\n\nimpl Flag for Stats {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"stats\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-stats\")\n }\n fn doc_category(&self) -> Category {\n Category::Logging\n }\n fn doc_short(&self) -> &'static str {\n r\"Print statistics about the search.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhen enabled, ripgrep will print aggregate statistics about the search. When\nthis flag is present, ripgrep will print at least the following stats to\nstdout at the end of the search: number of matched lines, number of files with\nmatches, number of files searched, and the time taken for the entire search to\ncomplete.\n.sp\nThis set of aggregate statistics may expand over time.\n.sp\nThis flag is always and implicitly enabled when \\flag{json} is used.\n.sp\nNote that this flag has no effect if \\flag{files}, \\flag{files-with-matches} or\n\\flag{files-without-match} is passed.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.stats = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_stats() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.stats);\n\n let args = parse_low_raw([\"--stats\"]).unwrap();\n assert_eq!(true, args.stats);\n\n let args = parse_low_raw([\"--stats\", \"--no-stats\"]).unwrap();\n assert_eq!(false, args.stats);\n}\n\n/// --stop-on-nonmatch\n#[derive(Debug)]\nstruct StopOnNonmatch;\n\nimpl Flag for StopOnNonmatch {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"stop-on-nonmatch\"\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"Stop searching after a non-match.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nEnabling this option will cause ripgrep to stop reading a file once it\nencounters a non-matching line after it has encountered a matching line.\nThis is useful if it is expected that all matches in a given file will be on\nsequential lines, for example due to the lines being sorted.\n.sp\nThis overrides the \\flag{multiline} flag.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--stop-on-nonmatch has no negation\");\n args.stop_on_nonmatch = true;\n args.multiline = false;\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_stop_on_nonmatch() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.stop_on_nonmatch);\n\n let args = parse_low_raw([\"--stop-on-nonmatch\"]).unwrap();\n assert_eq!(true, args.stop_on_nonmatch);\n\n let args = parse_low_raw([\"--stop-on-nonmatch\", \"-U\"]).unwrap();\n assert_eq!(true, args.multiline);\n assert_eq!(false, args.stop_on_nonmatch);\n\n let args = parse_low_raw([\"-U\", \"--stop-on-nonmatch\"]).unwrap();\n assert_eq!(false, args.multiline);\n assert_eq!(true, args.stop_on_nonmatch);\n\n let args =\n parse_low_raw([\"--stop-on-nonmatch\", \"--no-multiline\"]).unwrap();\n assert_eq!(false, args.multiline);\n assert_eq!(true, args.stop_on_nonmatch);\n}\n\n/// -a/--text\n#[derive(Debug)]\nstruct Text;\n\nimpl Flag for Text {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'a')\n }\n fn name_long(&self) -> &'static str {\n \"text\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-text\")\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"Search binary files as if they were text.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis flag instructs ripgrep to search binary files as if they were text. When\nthis flag is present, ripgrep's binary file detection is disabled. This means\nthat when a binary file is searched, its contents may be printed if there is\na match. This may cause escape codes to be printed that alter the behavior of\nyour terminal.\n.sp\nWhen binary file detection is enabled, it is imperfect. In general, it uses\na simple heuristic. If a \\fBNUL\\fP byte is seen during search, then the file\nis considered binary and searching stops (unless this flag is present).\nAlternatively, if the \\flag{binary} flag is used, then ripgrep will only quit\nwhen it sees a \\fBNUL\\fP byte after it sees a match (or searches the entire\nfile).\n.sp\nThis flag overrides the \\flag{binary} flag.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.binary = if v.unwrap_switch() {\n BinaryMode::AsText\n } else {\n BinaryMode::Auto\n };\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_text() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(BinaryMode::Auto, args.binary);\n\n let args = parse_low_raw([\"--text\"]).unwrap();\n assert_eq!(BinaryMode::AsText, args.binary);\n\n let args = parse_low_raw([\"-a\"]).unwrap();\n assert_eq!(BinaryMode::AsText, args.binary);\n\n let args = parse_low_raw([\"-a\", \"--no-text\"]).unwrap();\n assert_eq!(BinaryMode::Auto, args.binary);\n\n let args = parse_low_raw([\"-a\", \"--binary\"]).unwrap();\n assert_eq!(BinaryMode::SearchAndSuppress, args.binary);\n\n let args = parse_low_raw([\"--binary\", \"-a\"]).unwrap();\n assert_eq!(BinaryMode::AsText, args.binary);\n\n let args = parse_low_raw([\"-a\", \"--no-binary\"]).unwrap();\n assert_eq!(BinaryMode::Auto, args.binary);\n\n let args = parse_low_raw([\"--binary\", \"--no-text\"]).unwrap();\n assert_eq!(BinaryMode::Auto, args.binary);\n}\n\n/// -j/--threads\n#[derive(Debug)]\nstruct Threads;\n\nimpl Flag for Threads {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_short(&self) -> Option {\n Some(b'j')\n }\n fn name_long(&self) -> &'static str {\n \"threads\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"NUM\")\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"Set the approximate number of threads to use.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis flag sets the approximate number of threads to use. A value of \\fB0\\fP\n(which is the default) causes ripgrep to choose the thread count using\nheuristics.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let threads = convert::usize(&v.unwrap_value())?;\n args.threads = if threads == 0 { None } else { Some(threads) };\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_threads() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.threads);\n\n let args = parse_low_raw([\"--threads\", \"5\"]).unwrap();\n assert_eq!(Some(5), args.threads);\n\n let args = parse_low_raw([\"-j\", \"5\"]).unwrap();\n assert_eq!(Some(5), args.threads);\n\n let args = parse_low_raw([\"-j5\"]).unwrap();\n assert_eq!(Some(5), args.threads);\n\n let args = parse_low_raw([\"-j5\", \"-j10\"]).unwrap();\n assert_eq!(Some(10), args.threads);\n\n let args = parse_low_raw([\"-j5\", \"-j0\"]).unwrap();\n assert_eq!(None, args.threads);\n}\n\n/// --trace\n#[derive(Debug)]\nstruct Trace;\n\nimpl Flag for Trace {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"trace\"\n }\n fn doc_category(&self) -> Category {\n Category::Logging\n }\n fn doc_short(&self) -> &'static str {\n r\"Show trace messages.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nShow trace messages. This shows even more detail than the \\flag{debug}\nflag. Generally, one should only use this if \\flag{debug} doesn't emit the\ninformation you're looking for.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--trace can only be enabled\");\n args.logging = Some(LoggingMode::Trace);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_trace() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.logging);\n\n let args = parse_low_raw([\"--trace\"]).unwrap();\n assert_eq!(Some(LoggingMode::Trace), args.logging);\n\n let args = parse_low_raw([\"--debug\", \"--trace\"]).unwrap();\n assert_eq!(Some(LoggingMode::Trace), args.logging);\n}\n\n/// --trim\n#[derive(Debug)]\nstruct Trim;\n\nimpl Flag for Trim {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"trim\"\n }\n fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-trim\")\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Trim prefix whitespace from matches.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhen set, all ASCII whitespace at the beginning of each line printed will be\nremoved.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.trim = v.unwrap_switch();\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_trim() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.trim);\n\n let args = parse_low_raw([\"--trim\"]).unwrap();\n assert_eq!(true, args.trim);\n\n let args = parse_low_raw([\"--trim\", \"--no-trim\"]).unwrap();\n assert_eq!(false, args.trim);\n}\n\n/// -t/--type\n#[derive(Debug)]\nstruct Type;\n\nimpl Flag for Type {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_short(&self) -> Option {\n Some(b't')\n }\n fn name_long(&self) -> &'static str {\n \"type\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"TYPE\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Only search files matching TYPE.\"\n }\n fn doc_long(&self) -> &'static str {\n r#\"\nThis flag limits ripgrep to searching files matching \\fITYPE\\fP. Multiple\n\\flag{type} flags may be provided.\n.sp\nThis flag supports the special value \\fBall\\fP, which will behave as if\n\\flag{type} was provided for every file type supported by ripgrep (including\nany custom file types). The end result is that \\fB\\-\\-type=all\\fP causes\nripgrep to search in \"whitelist\" mode, where it will only search files it\nrecognizes via its type definitions.\n.sp\nNote that this flag has lower precedence than both the \\flag{glob} flag and\nany rules found in ignore files.\n.sp\nTo see the list of available file types, use the \\flag{type-list} flag.\n\"#\n }\n fn completion_type(&self) -> CompletionType {\n CompletionType::Filetype\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.type_changes.push(TypeChange::Select {\n name: convert::string(v.unwrap_value())?,\n });\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_type() {\n let select = |name: &str| TypeChange::Select { name: name.to_string() };\n\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(Vec::::new(), args.type_changes);\n\n let args = parse_low_raw([\"--type\", \"rust\"]).unwrap();\n assert_eq!(vec![select(\"rust\")], args.type_changes);\n\n let args = parse_low_raw([\"-t\", \"rust\"]).unwrap();\n assert_eq!(vec![select(\"rust\")], args.type_changes);\n\n let args = parse_low_raw([\"-trust\"]).unwrap();\n assert_eq!(vec![select(\"rust\")], args.type_changes);\n\n let args = parse_low_raw([\"-trust\", \"-tpython\"]).unwrap();\n assert_eq!(vec![select(\"rust\"), select(\"python\")], args.type_changes);\n\n let args = parse_low_raw([\"-tabcdefxyz\"]).unwrap();\n assert_eq!(vec![select(\"abcdefxyz\")], args.type_changes);\n}\n\n/// --type-add\n#[derive(Debug)]\nstruct TypeAdd;\n\nimpl Flag for TypeAdd {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"type-add\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"TYPESPEC\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Add a new glob for a file type.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis flag adds a new glob for a particular file type. Only one glob can be\nadded at a time. Multiple \\flag{type-add} flags can be provided. Unless\n\\flag{type-clear} is used, globs are added to any existing globs defined inside\nof ripgrep.\n.sp\nNote that this must be passed to every invocation of ripgrep. Type settings are\nnot persisted. See \\fBCONFIGURATION FILES\\fP for a workaround.\n.sp\nExample:\n.sp\n.EX\n rg \\-\\-type\\-add 'foo:*.foo' -tfoo \\fIPATTERN\\fP\n.EE\n.sp\nThis flag can also be used to include rules from other types with the special\ninclude directive. The include directive permits specifying one or more other\ntype names (separated by a comma) that have been defined and its rules will\nautomatically be imported into the type specified. For example, to create a\ntype called src that matches C++, Python and Markdown files, one can use:\n.sp\n.EX\n \\-\\-type\\-add 'src:include:cpp,py,md'\n.EE\n.sp\nAdditional glob rules can still be added to the src type by using this flag\nagain:\n.sp\n.EX\n \\-\\-type\\-add 'src:include:cpp,py,md' \\-\\-type\\-add 'src:*.foo'\n.EE\n.sp\nNote that type names must consist only of Unicode letters or numbers.\nPunctuation characters are not allowed.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.type_changes\n .push(TypeChange::Add { def: convert::string(v.unwrap_value())? });\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_type_add() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(Vec::::new(), args.type_changes);\n\n let args = parse_low_raw([\"--type-add\", \"foo\"]).unwrap();\n assert_eq!(\n vec![TypeChange::Add { def: \"foo\".to_string() }],\n args.type_changes\n );\n\n let args = parse_low_raw([\"--type-add\", \"foo\", \"--type-add=bar\"]).unwrap();\n assert_eq!(\n vec![\n TypeChange::Add { def: \"foo\".to_string() },\n TypeChange::Add { def: \"bar\".to_string() }\n ],\n args.type_changes\n );\n}\n\n/// --type-clear\n#[derive(Debug)]\nstruct TypeClear;\n\nimpl Flag for TypeClear {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_long(&self) -> &'static str {\n \"type-clear\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"TYPE\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Clear globs for a file type.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nClear the file type globs previously defined for \\fITYPE\\fP. This clears any\npreviously defined globs for the \\fITYPE\\fP, but globs can be added after this\nflag.\n.sp\nNote that this must be passed to every invocation of ripgrep. Type settings are\nnot persisted. See \\fBCONFIGURATION FILES\\fP for a workaround.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.type_changes.push(TypeChange::Clear {\n name: convert::string(v.unwrap_value())?,\n });\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_type_clear() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(Vec::::new(), args.type_changes);\n\n let args = parse_low_raw([\"--type-clear\", \"foo\"]).unwrap();\n assert_eq!(\n vec![TypeChange::Clear { name: \"foo\".to_string() }],\n args.type_changes\n );\n\n let args =\n parse_low_raw([\"--type-clear\", \"foo\", \"--type-clear=bar\"]).unwrap();\n assert_eq!(\n vec![\n TypeChange::Clear { name: \"foo\".to_string() },\n TypeChange::Clear { name: \"bar\".to_string() }\n ],\n args.type_changes\n );\n}\n\n/// --type-not\n#[derive(Debug)]\nstruct TypeNot;\n\nimpl Flag for TypeNot {\n fn is_switch(&self) -> bool {\n false\n }\n fn name_short(&self) -> Option {\n Some(b'T')\n }\n fn name_long(&self) -> &'static str {\n \"type-not\"\n }\n fn doc_variable(&self) -> Option<&'static str> {\n Some(\"TYPE\")\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r\"Do not search files matching TYPE.\"\n }\n fn doc_long(&self) -> &'static str {\n r#\"\nDo not search files matching \\fITYPE\\fP. Multiple \\flag{type-not} flags may be\nprovided. Use the \\flag{type-list} flag to list all available types.\n.sp\nThis flag supports the special value \\fBall\\fP, which will behave\nas if \\flag{type-not} was provided for every file type supported by\nripgrep (including any custom file types). The end result is that\n\\fB\\-\\-type\\-not=all\\fP causes ripgrep to search in \"blacklist\" mode, where it\nwill only search files that are unrecognized by its type definitions.\n.sp\nTo see the list of available file types, use the \\flag{type-list} flag.\n\"#\n }\n fn completion_type(&self) -> CompletionType {\n CompletionType::Filetype\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.type_changes.push(TypeChange::Negate {\n name: convert::string(v.unwrap_value())?,\n });\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_type_not() {\n let select = |name: &str| TypeChange::Select { name: name.to_string() };\n let negate = |name: &str| TypeChange::Negate { name: name.to_string() };\n\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(Vec::::new(), args.type_changes);\n\n let args = parse_low_raw([\"--type-not\", \"rust\"]).unwrap();\n assert_eq!(vec![negate(\"rust\")], args.type_changes);\n\n let args = parse_low_raw([\"-T\", \"rust\"]).unwrap();\n assert_eq!(vec![negate(\"rust\")], args.type_changes);\n\n let args = parse_low_raw([\"-Trust\"]).unwrap();\n assert_eq!(vec![negate(\"rust\")], args.type_changes);\n\n let args = parse_low_raw([\"-Trust\", \"-Tpython\"]).unwrap();\n assert_eq!(vec![negate(\"rust\"), negate(\"python\")], args.type_changes);\n\n let args = parse_low_raw([\"-Tabcdefxyz\"]).unwrap();\n assert_eq!(vec![negate(\"abcdefxyz\")], args.type_changes);\n\n let args = parse_low_raw([\"-Trust\", \"-ttoml\", \"-Tjson\"]).unwrap();\n assert_eq!(\n vec![negate(\"rust\"), select(\"toml\"), negate(\"json\")],\n args.type_changes\n );\n}\n\n/// --type-list\n#[derive(Debug)]\nstruct TypeList;\n\nimpl Flag for TypeList {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"type-list\"\n }\n fn doc_category(&self) -> Category {\n Category::OtherBehaviors\n }\n fn doc_short(&self) -> &'static str {\n r\"Show all supported file types.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nShow all supported file types and their corresponding globs. This takes any\n\\flag{type-add} and \\flag{type-clear} flags given into account. Each type is\nprinted on its own line, followed by a \\fB:\\fP and then a comma-delimited list\nof globs for that type on the same line.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--type-list has no negation\");\n args.mode.update(Mode::Types);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_type_list() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(Mode::Search(SearchMode::Standard), args.mode);\n\n let args = parse_low_raw([\"--type-list\"]).unwrap();\n assert_eq!(Mode::Types, args.mode);\n}\n\n/// -u/--unrestricted\n#[derive(Debug)]\nstruct Unrestricted;\n\nimpl Flag for Unrestricted {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'u')\n }\n fn name_long(&self) -> &'static str {\n \"unrestricted\"\n }\n fn doc_category(&self) -> Category {\n Category::Filter\n }\n fn doc_short(&self) -> &'static str {\n r#\"Reduce the level of \"smart\" filtering.\"#\n }\n fn doc_long(&self) -> &'static str {\n r#\"\nThis flag reduces the level of \"smart\" filtering. Repeated uses (up to 3) reduces\nthe filtering even more. When repeated three times, ripgrep will search every\nfile in a directory tree.\n.sp\nA single \\flag{unrestricted} flag is equivalent to \\flag{no-ignore}. Two\n\\flag{unrestricted} flags is equivalent to \\flag{no-ignore} \\flag{hidden}.\nThree \\flag{unrestricted} flags is equivalent to \\flag{no-ignore} \\flag{hidden}\n\\flag{binary}.\n.sp\nThe only filtering ripgrep still does when \\fB-uuu\\fP is given is to skip\nsymbolic links and to avoid printing matches from binary files. Symbolic links\ncan be followed via the \\flag{follow} flag, and binary files can be treated as\ntext files via the \\flag{text} flag.\n\"#\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--unrestricted has no negation\");\n args.unrestricted = args.unrestricted.saturating_add(1);\n anyhow::ensure!(\n args.unrestricted <= 3,\n \"flag can only be repeated up to 3 times\"\n );\n if args.unrestricted == 1 {\n NoIgnore.update(FlagValue::Switch(true), args)?;\n } else if args.unrestricted == 2 {\n Hidden.update(FlagValue::Switch(true), args)?;\n } else {\n assert_eq!(args.unrestricted, 3);\n Binary.update(FlagValue::Switch(true), args)?;\n }\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_unrestricted() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.no_ignore_vcs);\n assert_eq!(false, args.hidden);\n assert_eq!(BinaryMode::Auto, args.binary);\n\n let args = parse_low_raw([\"--unrestricted\"]).unwrap();\n assert_eq!(true, args.no_ignore_vcs);\n assert_eq!(false, args.hidden);\n assert_eq!(BinaryMode::Auto, args.binary);\n\n let args = parse_low_raw([\"--unrestricted\", \"-u\"]).unwrap();\n assert_eq!(true, args.no_ignore_vcs);\n assert_eq!(true, args.hidden);\n assert_eq!(BinaryMode::Auto, args.binary);\n\n let args = parse_low_raw([\"-uuu\"]).unwrap();\n assert_eq!(true, args.no_ignore_vcs);\n assert_eq!(true, args.hidden);\n assert_eq!(BinaryMode::SearchAndSuppress, args.binary);\n\n let result = parse_low_raw([\"-uuuu\"]);\n assert!(result.is_err(), \"{result:?}\");\n}\n\n/// --version\n#[derive(Debug)]\nstruct Version;\n\nimpl Flag for Version {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'V')\n }\n fn name_long(&self) -> &'static str {\n \"version\"\n }\n fn doc_category(&self) -> Category {\n Category::OtherBehaviors\n }\n fn doc_short(&self) -> &'static str {\n r\"Print ripgrep's version.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis flag prints ripgrep's version. This also may print other relevant\ninformation, such as the presence of target specific optimizations and the\n\\fBgit\\fP revision that this build of ripgrep was compiled from.\n\"\n }\n\n fn update(&self, v: FlagValue, _: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--version has no negation\");\n // Since this flag has different semantics for -V and --version and the\n // Flag trait doesn't support encoding this sort of thing, we handle it\n // as a special case in the parser.\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_version() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.special);\n\n let args = parse_low_raw([\"-V\"]).unwrap();\n assert_eq!(Some(SpecialMode::VersionShort), args.special);\n\n let args = parse_low_raw([\"--version\"]).unwrap();\n assert_eq!(Some(SpecialMode::VersionLong), args.special);\n\n let args = parse_low_raw([\"-V\", \"--version\"]).unwrap();\n assert_eq!(Some(SpecialMode::VersionLong), args.special);\n\n let args = parse_low_raw([\"--version\", \"-V\"]).unwrap();\n assert_eq!(Some(SpecialMode::VersionShort), args.special);\n}\n\n/// --vimgrep\n#[derive(Debug)]\nstruct Vimgrep;\n\nimpl Flag for Vimgrep {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_long(&self) -> &'static str {\n \"vimgrep\"\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Print results in a vim compatible format.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis flag instructs ripgrep to print results with every match on its own line,\nincluding line numbers and column numbers.\n.sp\nWith this option, a line with more than one match will be printed in its\nentirety more than once. For that reason, the total amount of output as a\nresult of this flag can be quadratic in the size of the input. For example,\nif the pattern matches every byte in an input file, then each line will be\nrepeated for every byte matched. For this reason, users should only use this\nflag when there is no other choice. Editor integrations should prefer some\nother way of reading results from ripgrep, such as via the \\flag{json} flag.\nOne alternative to avoiding exorbitant memory usage is to force ripgrep into\nsingle threaded mode with the \\flag{threads} flag. Note though that this will\nnot impact the total size of the output, just the heap memory that ripgrep will\nuse.\n\"\n }\n fn doc_choices(&self) -> &'static [&'static str] {\n &[]\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--vimgrep has no negation\");\n args.vimgrep = true;\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_vimgrep() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.vimgrep);\n\n let args = parse_low_raw([\"--vimgrep\"]).unwrap();\n assert_eq!(true, args.vimgrep);\n}\n\n/// --with-filename\n#[derive(Debug)]\nstruct WithFilename;\n\nimpl Flag for WithFilename {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'H')\n }\n fn name_long(&self) -> &'static str {\n \"with-filename\"\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Print the file path with each matching line.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis flag instructs ripgrep to print the file path for each matching line.\nThis is the default when more than one file is searched. If \\flag{heading} is\nenabled (the default when printing to a tty), the file path will be shown above\nclusters of matches from each file; otherwise, the file name will be shown as a\nprefix for each matched line.\n.sp\nThis flag overrides \\flag{no-filename}.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--with-filename has no defined negation\");\n args.with_filename = Some(true);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_with_filename() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.with_filename);\n\n let args = parse_low_raw([\"--with-filename\"]).unwrap();\n assert_eq!(Some(true), args.with_filename);\n\n let args = parse_low_raw([\"-H\"]).unwrap();\n assert_eq!(Some(true), args.with_filename);\n}\n\n/// --no-filename\n#[derive(Debug)]\nstruct WithFilenameNo;\n\nimpl Flag for WithFilenameNo {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'I')\n }\n fn name_long(&self) -> &'static str {\n \"no-filename\"\n }\n fn doc_category(&self) -> Category {\n Category::Output\n }\n fn doc_short(&self) -> &'static str {\n r\"Never print the path with each matching line.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nThis flag instructs ripgrep to never print the file path with each matching\nline. This is the default when ripgrep is explicitly instructed to search one\nfile or stdin.\n.sp\nThis flag overrides \\flag{with-filename}.\n\"\n }\n fn doc_choices(&self) -> &'static [&'static str] {\n &[]\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--no-filename has no defined negation\");\n args.with_filename = Some(false);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_with_filename_no() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.with_filename);\n\n let args = parse_low_raw([\"--no-filename\"]).unwrap();\n assert_eq!(Some(false), args.with_filename);\n\n let args = parse_low_raw([\"-I\"]).unwrap();\n assert_eq!(Some(false), args.with_filename);\n\n let args = parse_low_raw([\"-I\", \"-H\"]).unwrap();\n assert_eq!(Some(true), args.with_filename);\n\n let args = parse_low_raw([\"-H\", \"-I\"]).unwrap();\n assert_eq!(Some(false), args.with_filename);\n}\n\n/// -w/--word-regexp\n#[derive(Debug)]\nstruct WordRegexp;\n\nimpl Flag for WordRegexp {\n fn is_switch(&self) -> bool {\n true\n }\n fn name_short(&self) -> Option {\n Some(b'w')\n }\n fn name_long(&self) -> &'static str {\n \"word-regexp\"\n }\n fn doc_category(&self) -> Category {\n Category::Search\n }\n fn doc_short(&self) -> &'static str {\n r\"Show matches surrounded by word boundaries.\"\n }\n fn doc_long(&self) -> &'static str {\n r\"\nWhen enabled, ripgrep will only show matches surrounded by word boundaries.\nThis is equivalent to surrounding every pattern with \\fB\\\\b{start-half}\\fP and\n\\fB\\\\b{end-half}\\fP. These are a custom syntax from ripgrep's default regex\nengine that, unlike \\fB\\\\b\\fP, doesn't require matching a word character on one\nside. That is, \\fB\\\\b{start-half}\\fP corresponds to matching \\fB\\\\W|\\\\A\\fP on\nthe left and \\fB\\\\b{end-half}\\fP corresponds to matching \\fB\\\\W|\\\\z\\fP on the\nright.\n.sp\nThis overrides the \\flag{line-regexp} flag.\n\"\n }\n\n fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n assert!(v.unwrap_switch(), \"--word-regexp has no negation\");\n args.boundary = Some(BoundaryMode::Word);\n Ok(())\n }\n}\n\n#[cfg(test)]\n#[test]\nfn test_word_regexp() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(None, args.boundary);\n\n let args = parse_low_raw([\"--word-regexp\"]).unwrap();\n assert_eq!(Some(BoundaryMode::Word), args.boundary);\n\n let args = parse_low_raw([\"-w\"]).unwrap();\n assert_eq!(Some(BoundaryMode::Word), args.boundary);\n\n let args = parse_low_raw([\"-x\", \"-w\"]).unwrap();\n assert_eq!(Some(BoundaryMode::Word), args.boundary);\n\n let args = parse_low_raw([\"-w\", \"-x\"]).unwrap();\n assert_eq!(Some(BoundaryMode::Line), args.boundary);\n}\n\nfn check_indexing_allowed() -> anyhow::Result<()> {\n if cfg!(feature = \"unstable-index\") {\n return Ok(());\n }\n anyhow::bail!(\"{}\", crate::flags::INDEXING_NOT_SUPPORTED)\n}\n\nmod convert {\n use std::ffi::{OsStr, OsString};\n\n use anyhow::Context;\n\n pub(super) fn str(v: &OsStr) -> anyhow::Result<&str> {\n let Some(s) = v.to_str() else {\n anyhow::bail!(\"value is not valid UTF-8\")\n };\n Ok(s)\n }\n\n pub(super) fn string(v: OsString) -> anyhow::Result {\n let Ok(s) = v.into_string() else {\n anyhow::bail!(\"value is not valid UTF-8\")\n };\n Ok(s)\n }\n\n pub(super) fn usize(v: &OsStr) -> anyhow::Result {\n str(v)?.parse().context(\"value is not a valid number\")\n }\n\n pub(super) fn u64(v: &OsStr) -> anyhow::Result {\n str(v)?.parse().context(\"value is not a valid number\")\n }\n\n pub(super) fn human_readable_u64(v: &OsStr) -> anyhow::Result {\n grep::cli::parse_human_readable_size(str(v)?).context(\"invalid size\")\n }\n\n pub(super) fn human_readable_usize(v: &OsStr) -> anyhow::Result {\n let size = human_readable_u64(v)?;\n let Ok(size) = usize::try_from(size) else {\n anyhow::bail!(\"size is too big\")\n };\n Ok(size)\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn available_shorts() {\n let mut total = vec![false; 128];\n for byte in 0..=0x7F {\n match byte {\n b'.' | b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' => {\n total[usize::from(byte)] = true\n }\n _ => continue,\n }\n }\n\n let mut taken = vec![false; 128];\n for flag in FLAGS.iter() {\n let Some(short) = flag.name_short() else { continue };\n taken[usize::from(short)] = true;\n }\n\n for byte in 0..=0x7F {\n if total[usize::from(byte)] && !taken[usize::from(byte)] {\n eprintln!(\"{}\", char::from(byte));\n }\n }\n }\n\n #[test]\n fn shorts_all_ascii_alphanumeric() {\n for flag in FLAGS.iter() {\n let Some(byte) = flag.name_short() else { continue };\n let long = flag.name_long();\n assert!(\n byte.is_ascii_alphanumeric() || byte == b'.',\n \"\\\\x{byte:0X} is not a valid short flag for {long}\",\n )\n }\n }\n\n #[test]\n fn longs_all_ascii_alphanumeric() {\n for flag in FLAGS.iter() {\n let long = flag.name_long();\n let count = long.chars().count();\n assert!(count >= 2, \"flag '{long}' is less than 2 characters\");\n assert!(\n long.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'),\n \"flag '{long}' does not match ^[-0-9A-Za-z]+$\",\n );\n for alias in flag.aliases() {\n let count = alias.chars().count();\n assert!(\n count >= 2,\n \"flag '{long}' has alias '{alias}' that is \\\n less than 2 characters\",\n );\n assert!(\n alias\n .chars()\n .all(|c| c.is_ascii_alphanumeric() || c == '-'),\n \"flag '{long}' has alias '{alias}' that does not \\\n match ^[-0-9A-Za-z]+$\",\n );\n }\n let Some(negated) = flag.name_negated() else { continue };\n let count = negated.chars().count();\n assert!(\n count >= 2,\n \"flag '{long}' has negation '{negated}' that is \\\n less than 2 characters\",\n );\n assert!(\n negated.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'),\n \"flag '{long}' has negation '{negated}' that \\\n does not match ^[-0-9A-Za-z]+$\",\n );\n }\n }\n\n #[test]\n fn shorts_no_duplicates() {\n let mut taken = vec![false; 128];\n for flag in FLAGS.iter() {\n let Some(short) = flag.name_short() else { continue };\n let long = flag.name_long();\n assert!(\n !taken[usize::from(short)],\n \"flag {long} has duplicate short flag {}\",\n char::from(short)\n );\n taken[usize::from(short)] = true;\n }\n }\n\n #[test]\n fn longs_no_duplicates() {\n use std::collections::BTreeSet;\n\n let mut taken = BTreeSet::new();\n for flag in FLAGS.iter() {\n let long = flag.name_long();\n assert!(taken.insert(long), \"flag {long} has a duplicate name\");\n for alias in flag.aliases() {\n assert!(\n taken.insert(alias),\n \"flag {long} has an alias {alias} that is duplicative\"\n );\n }\n let Some(negated) = flag.name_negated() else { continue };\n assert!(\n taken.insert(negated),\n \"negated flag {negated} has a duplicate name\"\n );\n }\n }\n\n #[test]\n fn non_switches_have_variable_names() {\n for flag in FLAGS.iter() {\n if flag.is_switch() {\n continue;\n }\n let long = flag.name_long();\n assert!(\n flag.doc_variable().is_some(),\n \"flag '{long}' should have a variable name\"\n );\n }\n }\n\n #[test]\n fn switches_have_no_choices() {\n for flag in FLAGS.iter() {\n if !flag.is_switch() {\n continue;\n }\n let long = flag.name_long();\n let choices = flag.doc_choices();\n assert!(\n choices.is_empty(),\n \"switch flag '{long}' \\\n should not have any choices but has some: {choices:?}\",\n );\n }\n }\n\n #[test]\n fn choices_ascii_alphanumeric() {\n for flag in FLAGS.iter() {\n let long = flag.name_long();\n for choice in flag.doc_choices() {\n assert!(\n choice.chars().all(|c| c.is_ascii_alphanumeric()\n || c == '-'\n || c == ':'\n || c == '+'),\n \"choice '{choice}' for flag '{long}' does not match \\\n ^[-+:0-9A-Za-z]+$\",\n )\n }\n }\n }\n}", "messages": null, "tools": null} {"id": "850bc64f13733ed7", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/api/basic_json/json_base_class_t.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 1165, "sha256": "33bb5c84cb68510cc0e726eec6e74c7b2d0770bd1356b967fb277fde617dd5da", "text": "# nlohmann::basic_json::json_base_class_t\n\n```cpp\nusing json_base_class_t = detail::json_base_class;\n```\n\nThe base class used to inject custom functionality into each instance of `basic_json`.\nExamples of such functionality might be metadata, additional member functions (e.g., visitors), or other application-specific code.\n\n## Template parameters\n\n`CustomBaseClass`\n: the base class to be added to `basic_json`\n\n## Notes\n\n#### Default type\n\nThe default value for `CustomBaseClass` is `void`. In this case, an\n[empty base class](https://en.cppreference.com/w/cpp/language/ebo) is used and no additional functionality is injected.\n\n#### Limitations\n\nThe type `CustomBaseClass` has to be a default-constructible class.\n`basic_json` only supports copy/move construction/assignment if `CustomBaseClass` does so as well.\n\n## Examples\n\n??? example\n\n The following code shows how to inject custom data and methods for each node.\n \n ```cpp\n --8<-- \"examples/json_base_class_t.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/json_base_class_t.output\"\n ```\n\n## Version history\n\n- Added in version 3.12.0.", "messages": null, "tools": null} {"id": "8547c2c272763d14", "category": "code", "domain": "code", "source": "ripgrep", "license": "MIT OR Unlicense", "license_url": "https://spdx.org/licenses/MIT.html", "path": "crates/regex/src/config.rs", "lang": "rust", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/BurntSushi/ripgrep", "commit": "3fce3b5bb0236da2df6d99672afb8a719642eca7", "collector": "tools/harvest.py"}, "chars": 14471, "sha256": "e4fcae28c350a6100c002ad2872229272e7a82860da400b1c5b406736c81d351", "text": "use {\n grep_matcher::{ByteSet, LineTerminator},\n regex_automata::meta::Regex,\n regex_syntax::{\n ast,\n hir::{self, Hir},\n },\n};\n\nuse crate::{\n ast::AstAnalysis, ban, error::Error, non_matching::non_matching_bytes,\n strip::strip_from_match,\n};\n\n/// Config represents the configuration of a regex matcher in this crate.\n/// The configuration is itself a rough combination of the knobs found in\n/// the `regex` crate itself, along with additional `grep-matcher` specific\n/// options.\n///\n/// The configuration can be used to build a \"configured\" HIR expression. A\n/// configured HIR expression is an HIR expression that is aware of the\n/// configuration which generated it, and provides transformation on that HIR\n/// such that the configuration is preserved.\n#[derive(Clone, Debug)]\npub(crate) struct Config {\n pub(crate) case_insensitive: bool,\n pub(crate) case_smart: bool,\n pub(crate) multi_line: bool,\n pub(crate) dot_matches_new_line: bool,\n pub(crate) swap_greed: bool,\n pub(crate) ignore_whitespace: bool,\n pub(crate) unicode: bool,\n pub(crate) octal: bool,\n pub(crate) size_limit: usize,\n pub(crate) dfa_size_limit: usize,\n pub(crate) nest_limit: u32,\n pub(crate) line_terminator: Option,\n pub(crate) ban: Option,\n pub(crate) crlf: bool,\n pub(crate) word: bool,\n pub(crate) fixed_strings: bool,\n pub(crate) whole_line: bool,\n}\n\nimpl Default for Config {\n fn default() -> Config {\n Config {\n case_insensitive: false,\n case_smart: false,\n multi_line: false,\n dot_matches_new_line: false,\n swap_greed: false,\n ignore_whitespace: false,\n unicode: true,\n octal: false,\n // These size limits are much bigger than what's in the regex\n // crate by default.\n size_limit: 100 * (1 << 20),\n dfa_size_limit: 1000 * (1 << 20),\n nest_limit: 250,\n line_terminator: None,\n ban: None,\n crlf: false,\n word: false,\n fixed_strings: false,\n whole_line: false,\n }\n }\n}\n\nimpl Config {\n /// Use this configuration to build an HIR from the given patterns. The HIR\n /// returned corresponds to a single regex that is an alternation of the\n /// patterns given.\n pub(crate) fn build_many>(\n &self,\n patterns: &[P],\n ) -> Result {\n ConfiguredHIR::new(self.clone(), patterns)\n }\n\n /// Accounting for the `smart_case` config knob, return true if and only if\n /// this pattern should be matched case insensitively.\n fn is_case_insensitive(&self, analysis: &AstAnalysis) -> bool {\n if self.case_insensitive {\n return true;\n }\n if !self.case_smart {\n return false;\n }\n analysis.any_literal() && !analysis.any_uppercase()\n }\n\n /// Returns whether the given patterns should be treated as \"fixed strings\"\n /// literals. This is different from just querying the `fixed_strings` knob\n /// in that if the knob is false, this will still return true in some cases\n /// if the patterns are themselves indistinguishable from literals.\n ///\n /// The main idea here is that if this returns true, then it is safe\n /// to build an `regex_syntax::hir::Hir` value directly from the given\n /// patterns as an alternation of `hir::Literal` values.\n fn is_fixed_strings>(&self, patterns: &[P]) -> bool {\n // When these are enabled, we really need to parse the patterns and\n // let them go through the standard HIR translation process in order\n // for case folding transforms to be applied.\n if self.case_insensitive || self.case_smart {\n return false;\n }\n // Even if whole_line or word is enabled, both of those things can\n // be implemented by wrapping the Hir generated by an alternation of\n // fixed string literals. So for here at least, we don't care about the\n // word or whole_line settings.\n if self.fixed_strings {\n // ... but if any literal contains a line terminator, then we've\n // got to bail out because this will ultimately result in an error.\n if let Some(lineterm) = self.line_terminator {\n for p in patterns.iter() {\n if has_line_terminator(lineterm, p.as_ref()) {\n return false;\n }\n }\n }\n return true;\n }\n // In this case, the only way we can hand construct the Hir is if none\n // of the patterns contain meta characters. If they do, then we need to\n // send them through the standard parsing/translation process.\n for p in patterns.iter() {\n let p = p.as_ref();\n if p.chars().any(regex_syntax::is_meta_character) {\n return false;\n }\n // Same deal as when fixed_strings is set above. If the pattern has\n // a line terminator anywhere, then we need to bail out and let\n // an error occur.\n if let Some(lineterm) = self.line_terminator {\n if has_line_terminator(lineterm, p) {\n return false;\n }\n }\n }\n true\n }\n}\n\n/// A \"configured\" HIR expression, which is aware of the configuration which\n/// produced this HIR.\n///\n/// Since the configuration is tracked, values with this type can be\n/// transformed into other HIR expressions (or regular expressions) in a way\n/// that preserves the configuration. For example, the `fast_line_regex`\n/// method will apply literal extraction to the inner HIR and use that to build\n/// a new regex that matches the extracted literals in a way that is\n/// consistent with the configuration that produced this HIR. For example, the\n/// size limits set on the configured HIR will be propagated out to any\n/// subsequently constructed HIR or regular expression.\n#[derive(Clone, Debug)]\npub(crate) struct ConfiguredHIR {\n config: Config,\n hir: Hir,\n}\n\nimpl ConfiguredHIR {\n /// Parse the given patterns into a single HIR expression that represents\n /// an alternation of the patterns given.\n fn new>(\n config: Config,\n patterns: &[P],\n ) -> Result {\n let hir = if config.is_fixed_strings(patterns) {\n let mut alts = vec![];\n for p in patterns.iter() {\n alts.push(Hir::literal(p.as_ref().as_bytes()));\n }\n log::debug!(\n \"assembling HIR from {} fixed string literals\",\n alts.len()\n );\n let hir = Hir::alternation(alts);\n hir\n } else {\n let mut alts = vec![];\n for p in patterns.iter() {\n alts.push(if config.fixed_strings {\n format!(\"(?:{})\", regex_syntax::escape(p.as_ref()))\n } else {\n format!(\"(?:{})\", p.as_ref())\n });\n }\n let pattern = alts.join(\"|\");\n let ast = ast::parse::ParserBuilder::new()\n .nest_limit(config.nest_limit)\n .octal(config.octal)\n .ignore_whitespace(config.ignore_whitespace)\n .build()\n .parse(&pattern)\n .map_err(Error::generic)?;\n let analysis = AstAnalysis::from_ast(&ast);\n let mut hir = hir::translate::TranslatorBuilder::new()\n .utf8(false)\n .case_insensitive(config.is_case_insensitive(&analysis))\n .multi_line(config.multi_line)\n .dot_matches_new_line(config.dot_matches_new_line)\n .crlf(config.crlf)\n .swap_greed(config.swap_greed)\n .unicode(config.unicode)\n .build()\n .translate(&pattern, &ast)\n .map_err(Error::generic)?;\n if let Some(byte) = config.ban {\n ban::check(&hir, byte)?;\n }\n // We don't need to do this for the fixed-strings case above\n // because is_fixed_strings will return false if any pattern\n // contains a line terminator. Therefore, we don't need to strip\n // it.\n //\n // We go to some pains to avoid doing this in the fixed-strings\n // case because this can result in building a new HIR when ripgrep\n // is given a huge set of literals to search for. And this can\n // actually take a little time. It's not huge, but it's noticeable.\n hir = match config.line_terminator {\n None => hir,\n Some(line_term) => strip_from_match(hir, line_term)?,\n };\n hir\n };\n Ok(ConfiguredHIR { config, hir })\n }\n\n /// Return a reference to the underlying configuration.\n pub(crate) fn config(&self) -> &Config {\n &self.config\n }\n\n /// Return a reference to the underlying HIR.\n pub(crate) fn hir(&self) -> &Hir {\n &self.hir\n }\n\n /// Convert this HIR to a regex that can be used for matching.\n pub(crate) fn to_regex(&self) -> Result {\n let meta = Regex::config()\n .utf8_empty(false)\n .nfa_size_limit(Some(self.config.size_limit))\n // We don't expose a knob for this because the one-pass DFA is\n // usually not a perf bottleneck for ripgrep. But we give it some\n // extra room than the default.\n .onepass_size_limit(Some(10 * (1 << 20)))\n // Same deal here. The default limit for full DFAs is VERY small,\n // but with ripgrep we can afford to spend a bit more time on\n // building them I think.\n .dfa_size_limit(Some(1 * (1 << 20)))\n .dfa_state_limit(Some(1_000))\n .hybrid_cache_capacity(self.config.dfa_size_limit);\n Regex::builder()\n .configure(meta)\n .build_from_hir(&self.hir)\n .map_err(Error::regex)\n }\n\n /// Compute the set of non-matching bytes for this HIR expression.\n pub(crate) fn non_matching_bytes(&self) -> ByteSet {\n non_matching_bytes(&self.hir)\n }\n\n /// Returns the line terminator configured on this expression.\n ///\n /// When we have beginning/end anchors (NOT line anchors), the fast line\n /// searching path isn't quite correct. Or at least, doesn't match the slow\n /// path. Namely, the slow path strips line terminators while the fast path\n /// does not. Since '$' (when multi-line mode is disabled) doesn't match at\n /// line boundaries, the existence of a line terminator might cause it to\n /// not match when it otherwise would with the line terminator stripped.\n ///\n /// Since searching with text anchors is exceptionally rare in the context\n /// of line oriented searching (multi-line mode is basically always\n /// enabled), we just disable this optimization when there are text\n /// anchors. We disable it by not returning a line terminator, since\n /// without a line terminator, the fast search path can't be executed.\n ///\n /// Actually, the above is no longer quite correct. Later on, another\n /// optimization was added where if the line terminator was in the set of\n /// bytes that was guaranteed to never be part of a match, then the higher\n /// level search infrastructure assumes that the fast line-by-line search\n /// path can still be taken. This optimization applies when multi-line\n /// search (not multi-line mode) is enabled. In that case, there is no\n /// configured line terminator since the regex is permitted to match a\n /// line terminator. But if the regex is guaranteed to never match across\n /// multiple lines despite multi-line search being requested, we can still\n /// do the faster and more flexible line-by-line search. This is why the\n /// non-matching extraction routine removes `\\n` when `\\A` and `\\z` are\n /// present even though that's not quite correct...\n ///\n /// See: \n pub(crate) fn line_terminator(&self) -> Option {\n if self.hir.properties().look_set().contains_anchor_haystack() {\n None\n } else {\n self.config.line_terminator\n }\n }\n\n /// Turns this configured HIR into an equivalent one, but where it must\n /// match at the start and end of a line.\n pub(crate) fn into_whole_line(self) -> ConfiguredHIR {\n let line_anchor_start = Hir::look(self.line_anchor_start());\n let line_anchor_end = Hir::look(self.line_anchor_end());\n let hir =\n Hir::concat(vec![line_anchor_start, self.hir, line_anchor_end]);\n ConfiguredHIR { config: self.config, hir }\n }\n\n /// Turns this configured HIR into an equivalent one, but where it must\n /// match at word boundaries.\n pub(crate) fn into_word(self) -> ConfiguredHIR {\n let hir = Hir::concat(vec![\n Hir::look(if self.config.unicode {\n hir::Look::WordStartHalfUnicode\n } else {\n hir::Look::WordStartHalfAscii\n }),\n self.hir,\n Hir::look(if self.config.unicode {\n hir::Look::WordEndHalfUnicode\n } else {\n hir::Look::WordEndHalfAscii\n }),\n ]);\n ConfiguredHIR { config: self.config, hir }\n }\n\n /// Returns the \"start line\" anchor for this configuration.\n fn line_anchor_start(&self) -> hir::Look {\n if self.config.crlf {\n hir::Look::StartCRLF\n } else {\n hir::Look::StartLF\n }\n }\n\n /// Returns the \"end line\" anchor for this configuration.\n fn line_anchor_end(&self) -> hir::Look {\n if self.config.crlf { hir::Look::EndCRLF } else { hir::Look::EndLF }\n }\n}\n\n/// Returns true if the given literal string contains any byte from the line\n/// terminator given.\nfn has_line_terminator(lineterm: LineTerminator, literal: &str) -> bool {\n if lineterm.is_crlf() {\n literal.as_bytes().iter().copied().any(|b| b == b'\\r' || b == b'\\n')\n } else {\n literal.as_bytes().iter().copied().any(|b| b == lineterm.as_byte())\n }\n}", "messages": null, "tools": null} {"id": "85a64f673882cc68", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/to_bson.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 506, "sha256": "4af7213441024b73092f3aa1cae4ca2b4730191719ebe1d5724651336b3cdc44", "text": "#include \n#include \n#include \n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // create a JSON value\n json j = R\"({\"compact\": true, \"schema\": 0})\"_json;\n\n // serialize it to BSON\n std::vector v = json::to_bson(j);\n\n // print the vector content\n for (auto& byte : v)\n {\n std::cout << \"0x\" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << \" \";\n }\n std::cout << std::endl;\n}", "messages": null, "tools": null} {"id": "869ed28da14b0b89", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/src/unit-class_parser.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 92169, "sha256": "1004d9214be82e7ece565e09dc33689fb3cfcf47897b7f97f05acc450405f735", "text": "// __ _____ _____ _____\n// __| | __| | | | JSON for Modern C++ (supporting code)\n// | | |__ | | | | | | version 3.12.0\n// |_____|_____|_____|_|___| https://github.com/nlohmann/json\n//\n// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann \n// SPDX-License-Identifier: MIT\n\n#include \"doctest_compatibility.h\"\n\n#define JSON_TESTS_PRIVATE\n#include \nusing nlohmann::json;\n#ifdef JSON_TEST_NO_GLOBAL_UDLS\n using namespace nlohmann::literals; // NOLINT(google-build-using-namespace)\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace\n{\nclass SaxEventLogger\n{\n public:\n bool null()\n {\n events.emplace_back(\"null()\");\n return true;\n }\n\n bool boolean(bool val)\n {\n events.emplace_back(val ? \"boolean(true)\" : \"boolean(false)\");\n return true;\n }\n\n bool number_integer(json::number_integer_t val)\n {\n events.push_back(\"number_integer(\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_unsigned(json::number_unsigned_t val)\n {\n events.push_back(\"number_unsigned(\" + std::to_string(val) + \")\");\n return true;\n }\n\n bool number_float(json::number_float_t /*unused*/, const std::string& s)\n {\n events.push_back(\"number_float(\" + s + \")\");\n return true;\n }\n\n bool string(std::string& val)\n {\n events.push_back(\"string(\" + val + \")\");\n return true;\n }\n\n bool binary(json::binary_t& val)\n {\n std::string binary_contents = \"binary(\";\n std::string comma_space;\n for (auto b : val)\n {\n binary_contents.append(comma_space);\n binary_contents.append(std::to_string(static_cast(b)));\n comma_space = \", \";\n }\n binary_contents.append(\")\");\n events.push_back(binary_contents);\n return true;\n }\n\n bool start_object(std::size_t elements)\n {\n if (elements == (std::numeric_limits::max)())\n {\n events.emplace_back(\"start_object()\");\n }\n else\n {\n events.push_back(\"start_object(\" + std::to_string(elements) + \")\");\n }\n return true;\n }\n\n bool key(std::string& val)\n {\n events.push_back(\"key(\" + val + \")\");\n return true;\n }\n\n bool end_object()\n {\n events.emplace_back(\"end_object()\");\n return true;\n }\n\n bool start_array(std::size_t elements)\n {\n if (elements == (std::numeric_limits::max)())\n {\n events.emplace_back(\"start_array()\");\n }\n else\n {\n events.push_back(\"start_array(\" + std::to_string(elements) + \")\");\n }\n return true;\n }\n\n bool end_array()\n {\n events.emplace_back(\"end_array()\");\n return true;\n }\n\n bool parse_error(std::size_t position, const std::string& /*unused*/, const json::exception& /*unused*/)\n {\n errored = true;\n events.push_back(\"parse_error(\" + std::to_string(position) + \")\");\n return false;\n }\n\n std::vector events {}; // NOLINT(readability-redundant-member-init)\n bool errored = false;\n};\n\nclass SaxCountdown : public nlohmann::json::json_sax_t\n{\n public:\n explicit SaxCountdown(const int count) : events_left(count)\n {}\n\n bool null() override\n {\n return events_left-- > 0;\n }\n\n bool boolean(bool /*val*/) override\n {\n return events_left-- > 0;\n }\n\n bool number_integer(json::number_integer_t /*val*/) override\n {\n return events_left-- > 0;\n }\n\n bool number_unsigned(json::number_unsigned_t /*val*/) override\n {\n return events_left-- > 0;\n }\n\n bool number_float(json::number_float_t /*val*/, const std::string& /*s*/) override\n {\n return events_left-- > 0;\n }\n\n bool string(std::string& /*val*/) override\n {\n return events_left-- > 0;\n }\n\n bool binary(json::binary_t& /*val*/) override\n {\n return events_left-- > 0;\n }\n\n bool start_object(std::size_t /*elements*/) override\n {\n return events_left-- > 0;\n }\n\n bool key(std::string& /*val*/) override\n {\n return events_left-- > 0;\n }\n\n bool end_object() override\n {\n return events_left-- > 0;\n }\n\n bool start_array(std::size_t /*elements*/) override\n {\n return events_left-- > 0;\n }\n\n bool end_array() override\n {\n return events_left-- > 0;\n }\n\n bool parse_error(std::size_t /*position*/, const std::string& /*last_token*/, const json::exception& /*ex*/) override\n {\n return false;\n }\n\n private:\n int events_left = 0;\n};\n\njson parser_helper(const std::string& s);\nbool accept_helper(const std::string& s);\nvoid comments_helper(const std::string& s);\nvoid trailing_comma_helper(const std::string& s);\n\njson parser_helper(const std::string& s)\n{\n json j;\n json::parser(nlohmann::detail::input_adapter(s)).parse(true, j);\n\n // if this line was reached, no exception occurred\n // -> check if result is the same without exceptions\n json j_nothrow;\n CHECK_NOTHROW(json::parser(nlohmann::detail::input_adapter(s), nullptr, false).parse(true, j_nothrow));\n CHECK(j_nothrow == j);\n\n json j_sax;\n nlohmann::detail::json_sax_dom_parser sdp(j_sax);\n json::sax_parse(s, &sdp);\n CHECK(j_sax == j);\n\n comments_helper(s);\n\n trailing_comma_helper(s);\n\n return j;\n}\n\nbool accept_helper(const std::string& s)\n{\n CAPTURE(s)\n\n // 1. parse s without exceptions\n json j;\n CHECK_NOTHROW(json::parser(nlohmann::detail::input_adapter(s), nullptr, false).parse(true, j));\n const bool ok_noexcept = !j.is_discarded();\n\n // 2. accept s\n const bool ok_accept = json::parser(nlohmann::detail::input_adapter(s)).accept(true);\n\n // 3. check if both approaches come to the same result\n CHECK(ok_noexcept == ok_accept);\n\n // 4. parse with SAX (compare with relaxed accept result)\n SaxEventLogger el;\n CHECK_NOTHROW(json::sax_parse(s, &el, json::input_format_t::json, false));\n CHECK(json::parser(nlohmann::detail::input_adapter(s)).accept(false) == !el.errored);\n\n // 5. parse with simple callback\n json::parser_callback_t const cb = [](int /*unused*/, json::parse_event_t /*unused*/, json& /*unused*/) noexcept\n {\n return true;\n };\n json const j_cb = json::parse(s, cb, false);\n const bool ok_noexcept_cb = !j_cb.is_discarded();\n\n // 6. check if this approach came to the same result\n CHECK(ok_noexcept == ok_noexcept_cb);\n\n // 7. check if comments or trailing commas are properly ignored\n if (ok_accept)\n {\n comments_helper(s);\n trailing_comma_helper(s);\n }\n\n // 8. return result\n return ok_accept;\n}\n\nvoid comments_helper(const std::string& s)\n{\n json _;\n\n // parse/accept with default parser\n CHECK_NOTHROW(_ = json::parse(s));\n CHECK(json::accept(s));\n\n // parse/accept while skipping comments\n CHECK_NOTHROW(_ = json::parse(s, nullptr, false, true));\n CHECK(json::accept(s, true));\n\n std::vector json_with_comments;\n\n // start with a comment\n json_with_comments.push_back(std::string(\"// this is a comment\\n\") + s);\n json_with_comments.push_back(std::string(\"/* this is a comment */\") + s);\n // end with a comment\n json_with_comments.push_back(s + \"// this is a comment\");\n json_with_comments.push_back(s + \"/* this is a comment */\");\n\n // check all strings\n for (const auto& json_with_comment : json_with_comments)\n {\n CAPTURE(json_with_comment)\n CHECK_THROWS_AS(_ = json::parse(json_with_comment), json::parse_error);\n CHECK(!json::accept(json_with_comment));\n\n CHECK_NOTHROW(_ = json::parse(json_with_comment, nullptr, true, true));\n CHECK(json::accept(json_with_comment, true));\n }\n}\n\nvoid trailing_comma_helper(const std::string& s)\n{\n json _;\n\n // parse/accept with default parser\n CHECK_NOTHROW(_ = json::parse(s));\n CHECK(json::accept(s));\n\n // parse/accept while allowing trailing commas\n CHECK_NOTHROW(_ = json::parse(s, nullptr, false, false, true));\n CHECK(json::accept(s, false, true));\n\n // note: [,] and {,} are not allowed\n if (s.size() > 1 && (s.back() == ']' || s.back() == '}') && !_.empty())\n {\n std::vector json_with_trailing_commas;\n json_with_trailing_commas.push_back(s.substr(0, s.size() - 1) + \" ,\" + s.back());\n json_with_trailing_commas.push_back(s.substr(0, s.size() - 1) + \",\" + s.back());\n json_with_trailing_commas.push_back(s.substr(0, s.size() - 1) + \", \" + s.back());\n\n for (const auto& json_with_trailing_comma : json_with_trailing_commas)\n {\n CAPTURE(json_with_trailing_comma)\n CHECK_THROWS_AS(_ = json::parse(json_with_trailing_comma), json::parse_error);\n CHECK(!json::accept(json_with_trailing_comma));\n\n CHECK_NOTHROW(_ = json::parse(json_with_trailing_comma, nullptr, true, false, true));\n CHECK(json::accept(json_with_trailing_comma, false, true));\n }\n }\n}\n\n} // namespace\n\nTEST_CASE(\"parser class\")\n{\n SECTION(\"parse\")\n {\n SECTION(\"null\")\n {\n CHECK(parser_helper(\"null\") == json(nullptr));\n }\n\n SECTION(\"true\")\n {\n CHECK(parser_helper(\"true\") == json(true));\n }\n\n SECTION(\"false\")\n {\n CHECK(parser_helper(\"false\") == json(false));\n }\n\n SECTION(\"array\")\n {\n SECTION(\"empty array\")\n {\n CHECK(parser_helper(\"[]\") == json(json::value_t::array));\n CHECK(parser_helper(\"[ ]\") == json(json::value_t::array));\n }\n\n SECTION(\"nonempty array\")\n {\n CHECK(parser_helper(\"[true, false, null]\") == json({true, false, nullptr}));\n }\n }\n\n SECTION(\"object\")\n {\n SECTION(\"empty object\")\n {\n CHECK(parser_helper(\"{}\") == json(json::value_t::object));\n CHECK(parser_helper(\"{ }\") == json(json::value_t::object));\n }\n\n SECTION(\"nonempty object\")\n {\n CHECK(parser_helper(\"{\\\"\\\": true, \\\"one\\\": 1, \\\"two\\\": null}\") == json({{\"\", true}, {\"one\", 1}, {\"two\", nullptr}}));\n }\n }\n\n SECTION(\"string\")\n {\n // empty string\n CHECK(parser_helper(\"\\\"\\\"\") == json(json::value_t::string));\n\n SECTION(\"errors\")\n {\n // error: tab in string\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\t\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0009 (HT) must be escaped to \\\\u0009 or \\\\t; last read: '\\\"'\", json::parse_error&);\n // error: newline in string\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\n\\\"\"), \"[json.exception.parse_error.101] parse error at line 2, column 0: syntax error while parsing value - invalid string: control character U+000A (LF) must be escaped to \\\\u000A or \\\\n; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\r\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+000D (CR) must be escaped to \\\\u000D or \\\\r; last read: '\\\"'\", json::parse_error&);\n // error: backspace in string\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\b\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0008 (BS) must be escaped to \\\\u0008 or \\\\b; last read: '\\\"'\", json::parse_error&);\n // improve code coverage\n CHECK_THROWS_AS(parser_helper(\"\\uFF01\"), json::parse_error&);\n CHECK_THROWS_AS(parser_helper(\"[-4:1,]\"), json::parse_error&);\n // unescaped control characters\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x00\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: missing closing quote; last read: '\\\"'\", json::parse_error&); // NOLINT(bugprone-string-literal-with-embedded-nul)\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x01\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0001 (SOH) must be escaped to \\\\u0001; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x02\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0002 (STX) must be escaped to \\\\u0002; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x03\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0003 (ETX) must be escaped to \\\\u0003; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x04\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0004 (EOT) must be escaped to \\\\u0004; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x05\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0005 (ENQ) must be escaped to \\\\u0005; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x06\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0006 (ACK) must be escaped to \\\\u0006; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x07\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0007 (BEL) must be escaped to \\\\u0007; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x08\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0008 (BS) must be escaped to \\\\u0008 or \\\\b; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x09\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0009 (HT) must be escaped to \\\\u0009 or \\\\t; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x0a\\\"\"), \"[json.exception.parse_error.101] parse error at line 2, column 0: syntax error while parsing value - invalid string: control character U+000A (LF) must be escaped to \\\\u000A or \\\\n; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x0b\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+000B (VT) must be escaped to \\\\u000B; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x0c\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+000C (FF) must be escaped to \\\\u000C or \\\\f; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x0d\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+000D (CR) must be escaped to \\\\u000D or \\\\r; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x0e\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+000E (SO) must be escaped to \\\\u000E; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x0f\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+000F (SI) must be escaped to \\\\u000F; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x10\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0010 (DLE) must be escaped to \\\\u0010; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x11\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0011 (DC1) must be escaped to \\\\u0011; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x12\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0012 (DC2) must be escaped to \\\\u0012; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x13\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0013 (DC3) must be escaped to \\\\u0013; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x14\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0014 (DC4) must be escaped to \\\\u0014; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x15\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0015 (NAK) must be escaped to \\\\u0015; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x16\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0016 (SYN) must be escaped to \\\\u0016; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x17\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0017 (ETB) must be escaped to \\\\u0017; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x18\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0018 (CAN) must be escaped to \\\\u0018; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x19\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0019 (EM) must be escaped to \\\\u0019; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x1a\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+001A (SUB) must be escaped to \\\\u001A; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x1b\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+001B (ESC) must be escaped to \\\\u001B; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x1c\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+001C (FS) must be escaped to \\\\u001C; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x1d\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+001D (GS) must be escaped to \\\\u001D; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x1e\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+001E (RS) must be escaped to \\\\u001E; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\x1f\\\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+001F (US) must be escaped to \\\\u001F; last read: '\\\"'\", json::parse_error&);\n\n SECTION(\"additional test for null byte\")\n {\n // The test above for the null byte is wrong, because passing\n // a string to the parser only reads int until it encounters\n // a null byte. This test inserts the null byte later on and\n // uses an iterator range.\n std::string s = \"\\\"1\\\"\";\n s[1] = '\\0';\n json _;\n CHECK_THROWS_WITH_AS(_ = json::parse(s.begin(), s.end()), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0000 (NUL) must be escaped to \\\\u0000; last read: '\\\"'\", json::parse_error&);\n }\n }\n\n SECTION(\"escaped\")\n {\n // quotation mark \"\\\"\"\n auto r1 = R\"(\"\\\"\")\"_json;\n CHECK(parser_helper(\"\\\"\\\\\\\"\\\"\") == r1);\n // reverse solidus \"\\\\\"\n auto r2 = R\"(\"\\\\\")\"_json;\n CHECK(parser_helper(\"\\\"\\\\\\\\\\\"\") == r2);\n // solidus\n CHECK(parser_helper(\"\\\"\\\\/\\\"\") == R\"(\"/\")\"_json);\n // backspace\n CHECK(parser_helper(\"\\\"\\\\b\\\"\") == json(\"\\b\"));\n // formfeed\n CHECK(parser_helper(\"\\\"\\\\f\\\"\") == json(\"\\f\"));\n // newline\n CHECK(parser_helper(\"\\\"\\\\n\\\"\") == json(\"\\n\"));\n // carriage return\n CHECK(parser_helper(\"\\\"\\\\r\\\"\") == json(\"\\r\"));\n // horizontal tab\n CHECK(parser_helper(\"\\\"\\\\t\\\"\") == json(\"\\t\"));\n\n CHECK(parser_helper(\"\\\"\\\\u0001\\\"\").get() == \"\\x01\");\n CHECK(parser_helper(\"\\\"\\\\u000a\\\"\").get() == \"\\n\");\n CHECK(parser_helper(\"\\\"\\\\u00b0\\\"\").get() == \"°\");\n CHECK(parser_helper(\"\\\"\\\\u0c00\\\"\").get() == \"ఀ\");\n CHECK(parser_helper(\"\\\"\\\\ud000\\\"\").get() == \"퀀\");\n CHECK(parser_helper(\"\\\"\\\\u000E\\\"\").get() == \"\\x0E\");\n CHECK(parser_helper(\"\\\"\\\\u00F0\\\"\").get() == \"ð\");\n CHECK(parser_helper(\"\\\"\\\\u0100\\\"\").get() == \"Ā\");\n CHECK(parser_helper(\"\\\"\\\\u2000\\\"\").get() == \" \");\n CHECK(parser_helper(\"\\\"\\\\uFFFF\\\"\").get() == \"￿\");\n CHECK(parser_helper(\"\\\"\\\\u20AC\\\"\").get() == \"€\");\n CHECK(parser_helper(\"\\\"€\\\"\").get() == \"€\");\n CHECK(parser_helper(\"\\\"🎈\\\"\").get() == \"🎈\");\n\n CHECK(parser_helper(\"\\\"\\\\ud80c\\\\udc60\\\"\").get() == \"\\xf0\\x93\\x81\\xa0\");\n CHECK(parser_helper(\"\\\"\\\\ud83c\\\\udf1e\\\"\").get() == \"🌞\");\n }\n }\n\n SECTION(\"number\")\n {\n SECTION(\"integers\")\n {\n SECTION(\"without exponent\")\n {\n CHECK(parser_helper(\"-128\") == json(-128));\n CHECK(parser_helper(\"-0\") == json(-0));\n CHECK(parser_helper(\"0\") == json(0));\n CHECK(parser_helper(\"128\") == json(128));\n }\n\n SECTION(\"with exponent\")\n {\n CHECK(parser_helper(\"0e1\") == json(0e1));\n CHECK(parser_helper(\"0E1\") == json(0e1));\n\n CHECK(parser_helper(\"10000E-4\") == json(10000e-4));\n CHECK(parser_helper(\"10000E-3\") == json(10000e-3));\n CHECK(parser_helper(\"10000E-2\") == json(10000e-2));\n CHECK(parser_helper(\"10000E-1\") == json(10000e-1));\n CHECK(parser_helper(\"10000E0\") == json(10000e0));\n CHECK(parser_helper(\"10000E1\") == json(10000e1));\n CHECK(parser_helper(\"10000E2\") == json(10000e2));\n CHECK(parser_helper(\"10000E3\") == json(10000e3));\n CHECK(parser_helper(\"10000E4\") == json(10000e4));\n\n CHECK(parser_helper(\"10000e-4\") == json(10000e-4));\n CHECK(parser_helper(\"10000e-3\") == json(10000e-3));\n CHECK(parser_helper(\"10000e-2\") == json(10000e-2));\n CHECK(parser_helper(\"10000e-1\") == json(10000e-1));\n CHECK(parser_helper(\"10000e0\") == json(10000e0));\n CHECK(parser_helper(\"10000e1\") == json(10000e1));\n CHECK(parser_helper(\"10000e2\") == json(10000e2));\n CHECK(parser_helper(\"10000e3\") == json(10000e3));\n CHECK(parser_helper(\"10000e4\") == json(10000e4));\n\n CHECK(parser_helper(\"-0e1\") == json(-0e1));\n CHECK(parser_helper(\"-0E1\") == json(-0e1));\n CHECK(parser_helper(\"-0E123\") == json(-0e123));\n\n // numbers after exponent\n CHECK(parser_helper(\"10E0\") == json(10e0));\n CHECK(parser_helper(\"10E1\") == json(10e1));\n CHECK(parser_helper(\"10E2\") == json(10e2));\n CHECK(parser_helper(\"10E3\") == json(10e3));\n CHECK(parser_helper(\"10E4\") == json(10e4));\n CHECK(parser_helper(\"10E5\") == json(10e5));\n CHECK(parser_helper(\"10E6\") == json(10e6));\n CHECK(parser_helper(\"10E7\") == json(10e7));\n CHECK(parser_helper(\"10E8\") == json(10e8));\n CHECK(parser_helper(\"10E9\") == json(10e9));\n CHECK(parser_helper(\"10E+0\") == json(10e0));\n CHECK(parser_helper(\"10E+1\") == json(10e1));\n CHECK(parser_helper(\"10E+2\") == json(10e2));\n CHECK(parser_helper(\"10E+3\") == json(10e3));\n CHECK(parser_helper(\"10E+4\") == json(10e4));\n CHECK(parser_helper(\"10E+5\") == json(10e5));\n CHECK(parser_helper(\"10E+6\") == json(10e6));\n CHECK(parser_helper(\"10E+7\") == json(10e7));\n CHECK(parser_helper(\"10E+8\") == json(10e8));\n CHECK(parser_helper(\"10E+9\") == json(10e9));\n CHECK(parser_helper(\"10E-1\") == json(10e-1));\n CHECK(parser_helper(\"10E-2\") == json(10e-2));\n CHECK(parser_helper(\"10E-3\") == json(10e-3));\n CHECK(parser_helper(\"10E-4\") == json(10e-4));\n CHECK(parser_helper(\"10E-5\") == json(10e-5));\n CHECK(parser_helper(\"10E-6\") == json(10e-6));\n CHECK(parser_helper(\"10E-7\") == json(10e-7));\n CHECK(parser_helper(\"10E-8\") == json(10e-8));\n CHECK(parser_helper(\"10E-9\") == json(10e-9));\n }\n\n SECTION(\"edge cases\")\n {\n // From RFC8259, Section 6:\n // Note that when such software is used, numbers that are\n // integers and are in the range [-(2**53)+1, (2**53)-1]\n // are interoperable in the sense that implementations will\n // agree exactly on their numeric values.\n\n // -(2**53)+1\n CHECK(parser_helper(\"-9007199254740991\").get() == -9007199254740991);\n // (2**53)-1\n CHECK(parser_helper(\"9007199254740991\").get() == 9007199254740991);\n }\n\n SECTION(\"over the edge cases\") // issue #178 - Integer conversion to unsigned (incorrect handling of 64-bit integers)\n {\n // While RFC8259, Section 6 specifies a preference for support\n // for ranges in range of IEEE 754-2008 binary64 (double precision)\n // this does not accommodate 64-bit integers without loss of accuracy.\n // As 64-bit integers are now widely used in software, it is desirable\n // to expand support to the full 64 bit (signed and unsigned) range\n // i.e. -(2**63) -> (2**64)-1.\n\n // -(2**63) ** Note: compilers see negative literals as negated positive numbers (hence the -1))\n CHECK(parser_helper(\"-9223372036854775808\").get() == -9223372036854775807 - 1);\n // (2**63)-1\n CHECK(parser_helper(\"9223372036854775807\").get() == 9223372036854775807);\n // (2**64)-1\n CHECK(parser_helper(\"18446744073709551615\").get() == 18446744073709551615u);\n }\n }\n\n SECTION(\"floating-point\")\n {\n SECTION(\"without exponent\")\n {\n CHECK(parser_helper(\"-128.5\") == json(-128.5));\n CHECK(parser_helper(\"0.999\") == json(0.999));\n CHECK(parser_helper(\"128.5\") == json(128.5));\n CHECK(parser_helper(\"-0.0\") == json(-0.0));\n }\n\n SECTION(\"with exponent\")\n {\n CHECK(parser_helper(\"-128.5E3\") == json(-128.5E3));\n CHECK(parser_helper(\"-128.5E-3\") == json(-128.5E-3));\n CHECK(parser_helper(\"-0.0e1\") == json(-0.0e1));\n CHECK(parser_helper(\"-0.0E1\") == json(-0.0e1));\n }\n }\n\n SECTION(\"overflow\")\n {\n // overflows during parsing yield an exception\n CHECK_THROWS_WITH_AS(parser_helper(\"1.18973e+4932\").empty(), \"[json.exception.out_of_range.406] number overflow parsing '1.18973e+4932'\", json::out_of_range&);\n }\n\n SECTION(\"invalid numbers\")\n {\n // numbers must not begin with \"+\"\n CHECK_THROWS_AS(parser_helper(\"+1\"), json::parse_error&);\n CHECK_THROWS_AS(parser_helper(\"+0\"), json::parse_error&);\n\n CHECK_THROWS_WITH_AS(parser_helper(\"01\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - unexpected number literal; expected end of input\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"-01\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - unexpected number literal; expected end of input\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"--1\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid number; expected digit after '-'; last read: '--'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"1.\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid number; expected digit after '.'; last read: '1.'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"1E\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid number; expected '+', '-', or digit after exponent; last read: '1E'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"1E-\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 4: syntax error while parsing value - invalid number; expected digit after exponent sign; last read: '1E-'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"1.E1\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid number; expected digit after '.'; last read: '1.E'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"-1E\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 4: syntax error while parsing value - invalid number; expected '+', '-', or digit after exponent; last read: '-1E'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"-0E#\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 4: syntax error while parsing value - invalid number; expected '+', '-', or digit after exponent; last read: '-0E#'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"-0E-#\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 5: syntax error while parsing value - invalid number; expected digit after exponent sign; last read: '-0E-#'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"-0#\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid literal; last read: '-0#'; expected end of input\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"-0.0:\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 5: syntax error while parsing value - unexpected ':'; expected end of input\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"-0.0Z\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 5: syntax error while parsing value - invalid literal; last read: '-0.0Z'; expected end of input\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"-0E123:\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 7: syntax error while parsing value - unexpected ':'; expected end of input\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"-0e0-:\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 6: syntax error while parsing value - invalid number; expected digit after '-'; last read: '-:'; expected end of input\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"-0e-:\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 5: syntax error while parsing value - invalid number; expected digit after exponent sign; last read: '-0e-:'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"-0f\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 4: syntax error while parsing value - invalid literal; last read: '-0f'; expected end of input\", json::parse_error&);\n }\n }\n }\n\n SECTION(\"accept\")\n {\n SECTION(\"null\")\n {\n CHECK(accept_helper(\"null\"));\n }\n\n SECTION(\"true\")\n {\n CHECK(accept_helper(\"true\"));\n }\n\n SECTION(\"false\")\n {\n CHECK(accept_helper(\"false\"));\n }\n\n SECTION(\"array\")\n {\n SECTION(\"empty array\")\n {\n CHECK(accept_helper(\"[]\"));\n CHECK(accept_helper(\"[ ]\"));\n }\n\n SECTION(\"nonempty array\")\n {\n CHECK(accept_helper(\"[true, false, null]\"));\n }\n }\n\n SECTION(\"object\")\n {\n SECTION(\"empty object\")\n {\n CHECK(accept_helper(\"{}\"));\n CHECK(accept_helper(\"{ }\"));\n }\n\n SECTION(\"nonempty object\")\n {\n CHECK(accept_helper(\"{\\\"\\\": true, \\\"one\\\": 1, \\\"two\\\": null}\"));\n }\n }\n\n SECTION(\"string\")\n {\n // empty string\n CHECK(accept_helper(\"\\\"\\\"\"));\n\n SECTION(\"errors\")\n {\n // error: tab in string\n CHECK(accept_helper(\"\\\"\\t\\\"\") == false);\n // error: newline in string\n CHECK(accept_helper(\"\\\"\\n\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\r\\\"\") == false);\n // error: backspace in string\n CHECK(accept_helper(\"\\\"\\b\\\"\") == false);\n // improve code coverage\n CHECK(accept_helper(\"\\uFF01\") == false);\n CHECK(accept_helper(\"[-4:1,]\") == false);\n // unescaped control characters\n CHECK(accept_helper(\"\\\"\\x00\\\"\") == false); // NOLINT(bugprone-string-literal-with-embedded-nul)\n CHECK(accept_helper(\"\\\"\\x01\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x02\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x03\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x04\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x05\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x06\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x07\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x08\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x09\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x0a\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x0b\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x0c\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x0d\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x0e\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x0f\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x10\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x11\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x12\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x13\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x14\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x15\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x16\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x17\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x18\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x19\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x1a\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x1b\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x1c\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x1d\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x1e\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\x1f\\\"\") == false);\n }\n\n SECTION(\"escaped\")\n {\n // quotation mark \"\\\"\"\n auto r1 = R\"(\"\\\"\")\"_json;\n CHECK(accept_helper(\"\\\"\\\\\\\"\\\"\"));\n // reverse solidus \"\\\\\"\n auto r2 = R\"(\"\\\\\")\"_json;\n CHECK(accept_helper(\"\\\"\\\\\\\\\\\"\"));\n // solidus\n CHECK(accept_helper(\"\\\"\\\\/\\\"\"));\n // backspace\n CHECK(accept_helper(\"\\\"\\\\b\\\"\"));\n // formfeed\n CHECK(accept_helper(\"\\\"\\\\f\\\"\"));\n // newline\n CHECK(accept_helper(\"\\\"\\\\n\\\"\"));\n // carriage return\n CHECK(accept_helper(\"\\\"\\\\r\\\"\"));\n // horizontal tab\n CHECK(accept_helper(\"\\\"\\\\t\\\"\"));\n\n CHECK(accept_helper(\"\\\"\\\\u0001\\\"\"));\n CHECK(accept_helper(\"\\\"\\\\u000a\\\"\"));\n CHECK(accept_helper(\"\\\"\\\\u00b0\\\"\"));\n CHECK(accept_helper(\"\\\"\\\\u0c00\\\"\"));\n CHECK(accept_helper(\"\\\"\\\\ud000\\\"\"));\n CHECK(accept_helper(\"\\\"\\\\u000E\\\"\"));\n CHECK(accept_helper(\"\\\"\\\\u00F0\\\"\"));\n CHECK(accept_helper(\"\\\"\\\\u0100\\\"\"));\n CHECK(accept_helper(\"\\\"\\\\u2000\\\"\"));\n CHECK(accept_helper(\"\\\"\\\\uFFFF\\\"\"));\n CHECK(accept_helper(\"\\\"\\\\u20AC\\\"\"));\n CHECK(accept_helper(\"\\\"€\\\"\"));\n CHECK(accept_helper(\"\\\"🎈\\\"\"));\n\n CHECK(accept_helper(\"\\\"\\\\ud80c\\\\udc60\\\"\"));\n CHECK(accept_helper(\"\\\"\\\\ud83c\\\\udf1e\\\"\"));\n }\n }\n\n SECTION(\"number\")\n {\n SECTION(\"integers\")\n {\n SECTION(\"without exponent\")\n {\n CHECK(accept_helper(\"-128\"));\n CHECK(accept_helper(\"-0\"));\n CHECK(accept_helper(\"0\"));\n CHECK(accept_helper(\"128\"));\n }\n\n SECTION(\"with exponent\")\n {\n CHECK(accept_helper(\"0e1\"));\n CHECK(accept_helper(\"0E1\"));\n\n CHECK(accept_helper(\"10000E-4\"));\n CHECK(accept_helper(\"10000E-3\"));\n CHECK(accept_helper(\"10000E-2\"));\n CHECK(accept_helper(\"10000E-1\"));\n CHECK(accept_helper(\"10000E0\"));\n CHECK(accept_helper(\"10000E1\"));\n CHECK(accept_helper(\"10000E2\"));\n CHECK(accept_helper(\"10000E3\"));\n CHECK(accept_helper(\"10000E4\"));\n\n CHECK(accept_helper(\"10000e-4\"));\n CHECK(accept_helper(\"10000e-3\"));\n CHECK(accept_helper(\"10000e-2\"));\n CHECK(accept_helper(\"10000e-1\"));\n CHECK(accept_helper(\"10000e0\"));\n CHECK(accept_helper(\"10000e1\"));\n CHECK(accept_helper(\"10000e2\"));\n CHECK(accept_helper(\"10000e3\"));\n CHECK(accept_helper(\"10000e4\"));\n\n CHECK(accept_helper(\"-0e1\"));\n CHECK(accept_helper(\"-0E1\"));\n CHECK(accept_helper(\"-0E123\"));\n }\n\n SECTION(\"edge cases\")\n {\n // From RFC8259, Section 6:\n // Note that when such software is used, numbers that are\n // integers and are in the range [-(2**53)+1, (2**53)-1]\n // are interoperable in the sense that implementations will\n // agree exactly on their numeric values.\n\n // -(2**53)+1\n CHECK(accept_helper(\"-9007199254740991\"));\n // (2**53)-1\n CHECK(accept_helper(\"9007199254740991\"));\n }\n\n SECTION(\"over the edge cases\") // issue #178 - Integer conversion to unsigned (incorrect handling of 64-bit integers)\n {\n // While RFC8259, Section 6 specifies a preference for support\n // for ranges in range of IEEE 754-2008 binary64 (double precision)\n // this does not accommodate 64 bit integers without loss of accuracy.\n // As 64 bit integers are now widely used in software, it is desirable\n // to expand support to the full 64 bit (signed and unsigned) range\n // i.e. -(2**63) -> (2**64)-1.\n\n // -(2**63) ** Note: compilers see negative literals as negated positive numbers (hence the -1))\n CHECK(accept_helper(\"-9223372036854775808\"));\n // (2**63)-1\n CHECK(accept_helper(\"9223372036854775807\"));\n // (2**64)-1\n CHECK(accept_helper(\"18446744073709551615\"));\n }\n }\n\n SECTION(\"floating-point\")\n {\n SECTION(\"without exponent\")\n {\n CHECK(accept_helper(\"-128.5\"));\n CHECK(accept_helper(\"0.999\"));\n CHECK(accept_helper(\"128.5\"));\n CHECK(accept_helper(\"-0.0\"));\n }\n\n SECTION(\"with exponent\")\n {\n CHECK(accept_helper(\"-128.5E3\"));\n CHECK(accept_helper(\"-128.5E-3\"));\n CHECK(accept_helper(\"-0.0e1\"));\n CHECK(accept_helper(\"-0.0E1\"));\n }\n }\n\n SECTION(\"overflow\")\n {\n // overflows during parsing\n CHECK(!accept_helper(\"1.18973e+4932\"));\n }\n\n SECTION(\"invalid numbers\")\n {\n CHECK(accept_helper(\"01\") == false);\n CHECK(accept_helper(\"--1\") == false);\n CHECK(accept_helper(\"1.\") == false);\n CHECK(accept_helper(\"1E\") == false);\n CHECK(accept_helper(\"1E-\") == false);\n CHECK(accept_helper(\"1.E1\") == false);\n CHECK(accept_helper(\"-1E\") == false);\n CHECK(accept_helper(\"-0E#\") == false);\n CHECK(accept_helper(\"-0E-#\") == false);\n CHECK(accept_helper(\"-0#\") == false);\n CHECK(accept_helper(\"-0.0:\") == false);\n CHECK(accept_helper(\"-0.0Z\") == false);\n CHECK(accept_helper(\"-0E123:\") == false);\n CHECK(accept_helper(\"-0e0-:\") == false);\n CHECK(accept_helper(\"-0e-:\") == false);\n CHECK(accept_helper(\"-0f\") == false);\n\n // numbers must not begin with \"+\"\n CHECK(accept_helper(\"+1\") == false);\n CHECK(accept_helper(\"+0\") == false);\n }\n }\n }\n\n SECTION(\"parse errors\")\n {\n // unexpected end of number\n CHECK_THROWS_WITH_AS(parser_helper(\"0.\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid number; expected digit after '.'; last read: '0.'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"-\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid number; expected digit after '-'; last read: '-'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"--\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid number; expected digit after '-'; last read: '--'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"-0.\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 4: syntax error while parsing value - invalid number; expected digit after '.'; last read: '-0.'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"-.\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid number; expected digit after '-'; last read: '-.'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"-:\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid number; expected digit after '-'; last read: '-:'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"0.:\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid number; expected digit after '.'; last read: '0.:'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"e.\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 1: syntax error while parsing value - invalid literal; last read: 'e'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"1e.\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid number; expected '+', '-', or digit after exponent; last read: '1e.'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"1e/\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid number; expected '+', '-', or digit after exponent; last read: '1e/'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"1e:\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid number; expected '+', '-', or digit after exponent; last read: '1e:'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"1E.\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid number; expected '+', '-', or digit after exponent; last read: '1E.'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"1E/\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid number; expected '+', '-', or digit after exponent; last read: '1E/'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"1E:\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid number; expected '+', '-', or digit after exponent; last read: '1E:'\", json::parse_error&);\n\n // unexpected end of null\n CHECK_THROWS_WITH_AS(parser_helper(\"n\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid literal; last read: 'n'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"nu\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid literal; last read: 'nu'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"nul\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 4: syntax error while parsing value - invalid literal; last read: 'nul'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"nulk\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 4: syntax error while parsing value - invalid literal; last read: 'nulk'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"nulm\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 4: syntax error while parsing value - invalid literal; last read: 'nulm'\", json::parse_error&);\n\n // unexpected end of true\n CHECK_THROWS_WITH_AS(parser_helper(\"t\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid literal; last read: 't'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"tr\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid literal; last read: 'tr'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"tru\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 4: syntax error while parsing value - invalid literal; last read: 'tru'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"trud\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 4: syntax error while parsing value - invalid literal; last read: 'trud'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"truf\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 4: syntax error while parsing value - invalid literal; last read: 'truf'\", json::parse_error&);\n\n // unexpected end of false\n CHECK_THROWS_WITH_AS(parser_helper(\"f\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid literal; last read: 'f'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"fa\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid literal; last read: 'fa'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"fal\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 4: syntax error while parsing value - invalid literal; last read: 'fal'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"fals\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 5: syntax error while parsing value - invalid literal; last read: 'fals'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"falsd\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 5: syntax error while parsing value - invalid literal; last read: 'falsd'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"falsf\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 5: syntax error while parsing value - invalid literal; last read: 'falsf'\", json::parse_error&);\n\n // missing/unexpected end of array\n CHECK_THROWS_WITH_AS(parser_helper(\"[\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - unexpected end of input; expected '[', '{', or a literal\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"[1\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing array - unexpected end of input; expected ']'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"[1,\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 4: syntax error while parsing value - unexpected end of input; expected '[', '{', or a literal\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"[1,]\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 4: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"]\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 1: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal\", json::parse_error&);\n\n // missing/unexpected end of object\n CHECK_THROWS_WITH_AS(parser_helper(\"{\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing object key - unexpected end of input; expected string literal\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"{\\\"foo\\\"\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 7: syntax error while parsing object separator - unexpected end of input; expected ':'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"{\\\"foo\\\":\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected end of input; expected '[', '{', or a literal\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"{\\\"foo\\\":}\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected '}'; expected '[', '{', or a literal\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"{\\\"foo\\\":1,}\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 10: syntax error while parsing object key - unexpected '}'; expected string literal\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"}\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 1: syntax error while parsing value - unexpected '}'; expected '[', '{', or a literal\", json::parse_error&);\n\n // missing/unexpected end of string\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: missing closing quote; last read: '\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\\\\\\"\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 4: syntax error while parsing value - invalid string: missing closing quote; last read: '\\\"\\\\\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\\\u\\\"\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 4: syntax error while parsing value - invalid string: '\\\\u' must be followed by 4 hex digits; last read: '\\\"\\\\u\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\\\u0\\\"\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 5: syntax error while parsing value - invalid string: '\\\\u' must be followed by 4 hex digits; last read: '\\\"\\\\u0\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\\\u01\\\"\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 6: syntax error while parsing value - invalid string: '\\\\u' must be followed by 4 hex digits; last read: '\\\"\\\\u01\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\\\u012\\\"\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 7: syntax error while parsing value - invalid string: '\\\\u' must be followed by 4 hex digits; last read: '\\\"\\\\u012\\\"'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\\\u\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 4: syntax error while parsing value - invalid string: '\\\\u' must be followed by 4 hex digits; last read: '\\\"\\\\u'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\\\u0\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 5: syntax error while parsing value - invalid string: '\\\\u' must be followed by 4 hex digits; last read: '\\\"\\\\u0'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\\\u01\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 6: syntax error while parsing value - invalid string: '\\\\u' must be followed by 4 hex digits; last read: '\\\"\\\\u01'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(parser_helper(\"\\\"\\\\u012\"),\n \"[json.exception.parse_error.101] parse error at line 1, column 7: syntax error while parsing value - invalid string: '\\\\u' must be followed by 4 hex digits; last read: '\\\"\\\\u012'\", json::parse_error&);\n\n // invalid escapes\n for (int c = 1; c < 128; ++c)\n {\n auto s = std::string(\"\\\"\\\\\") + std::string(1, static_cast(c)) + \"\\\"\";\n\n switch (c)\n {\n // valid escapes\n case ('\"'):\n case ('\\\\'):\n case ('/'):\n case ('b'):\n case ('f'):\n case ('n'):\n case ('r'):\n case ('t'):\n {\n CHECK_NOTHROW(parser_helper(s));\n break;\n }\n\n // \\u must be followed with four numbers, so we skip it here\n case ('u'):\n {\n break;\n }\n\n // any other combination of backslash and character is invalid\n default:\n {\n CHECK_THROWS_AS(parser_helper(s), json::parse_error&);\n // only check error message if c is not a control character\n if (c > 0x1f)\n {\n CHECK_THROWS_WITH_STD_STR(parser_helper(s),\n \"[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid string: forbidden character after backslash; last read: '\\\"\\\\\" + std::string(1, static_cast(c)) + \"'\");\n }\n break;\n }\n }\n }\n\n // invalid \\uxxxx escapes\n {\n // check whether character is a valid hex character\n const auto valid = [](int c)\n {\n switch (c)\n {\n case ('0'):\n case ('1'):\n case ('2'):\n case ('3'):\n case ('4'):\n case ('5'):\n case ('6'):\n case ('7'):\n case ('8'):\n case ('9'):\n case ('a'):\n case ('b'):\n case ('c'):\n case ('d'):\n case ('e'):\n case ('f'):\n case ('A'):\n case ('B'):\n case ('C'):\n case ('D'):\n case ('E'):\n case ('F'):\n {\n return true;\n }\n\n default:\n {\n return false;\n }\n }\n };\n\n for (int c = 1; c < 128; ++c)\n {\n std::string const s = \"\\\"\\\\u\";\n\n // create a string with the iterated character at each position\n auto s1 = s + \"000\" + std::string(1, static_cast(c)) + \"\\\"\";\n auto s2 = s + \"00\" + std::string(1, static_cast(c)) + \"0\\\"\";\n auto s3 = s + \"0\" + std::string(1, static_cast(c)) + \"00\\\"\";\n auto s4 = s + std::string(1, static_cast(c)) + \"000\\\"\";\n\n if (valid(c))\n {\n CAPTURE(s1)\n CHECK_NOTHROW(parser_helper(s1));\n CAPTURE(s2)\n CHECK_NOTHROW(parser_helper(s2));\n CAPTURE(s3)\n CHECK_NOTHROW(parser_helper(s3));\n CAPTURE(s4)\n CHECK_NOTHROW(parser_helper(s4));\n }\n else\n {\n CAPTURE(s1)\n CHECK_THROWS_AS(parser_helper(s1), json::parse_error&);\n // only check error message if c is not a control character\n if (c > 0x1f)\n {\n CHECK_THROWS_WITH_STD_STR(parser_helper(s1),\n \"[json.exception.parse_error.101] parse error at line 1, column 7: syntax error while parsing value - invalid string: '\\\\u' must be followed by 4 hex digits; last read: '\" + s1.substr(0, 7) + \"'\");\n }\n\n CAPTURE(s2)\n CHECK_THROWS_AS(parser_helper(s2), json::parse_error&);\n // only check error message if c is not a control character\n if (c > 0x1f)\n {\n CHECK_THROWS_WITH_STD_STR(parser_helper(s2),\n \"[json.exception.parse_error.101] parse error at line 1, column 6: syntax error while parsing value - invalid string: '\\\\u' must be followed by 4 hex digits; last read: '\" + s2.substr(0, 6) + \"'\");\n }\n\n CAPTURE(s3)\n CHECK_THROWS_AS(parser_helper(s3), json::parse_error&);\n // only check error message if c is not a control character\n if (c > 0x1f)\n {\n CHECK_THROWS_WITH_STD_STR(parser_helper(s3),\n \"[json.exception.parse_error.101] parse error at line 1, column 5: syntax error while parsing value - invalid string: '\\\\u' must be followed by 4 hex digits; last read: '\" + s3.substr(0, 5) + \"'\");\n }\n\n CAPTURE(s4)\n CHECK_THROWS_AS(parser_helper(s4), json::parse_error&);\n // only check error message if c is not a control character\n if (c > 0x1f)\n {\n CHECK_THROWS_WITH_STD_STR(parser_helper(s4),\n \"[json.exception.parse_error.101] parse error at line 1, column 4: syntax error while parsing value - invalid string: '\\\\u' must be followed by 4 hex digits; last read: '\" + s4.substr(0, 4) + \"'\");\n }\n }\n }\n }\n\n json _;\n\n // missing part of a surrogate pair\n CHECK_THROWS_WITH_AS(_ = json::parse(\"\\\"\\\\uD80C\\\"\"), \"[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: '\\\"\\\\uD80C\\\"'\", json::parse_error&);\n // invalid surrogate pair\n CHECK_THROWS_WITH_AS(_ = json::parse(\"\\\"\\\\uD80C\\\\uD80C\\\"\"),\n \"[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: '\\\"\\\\uD80C\\\\uD80C'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(_ = json::parse(\"\\\"\\\\uD80C\\\\u0000\\\"\"),\n \"[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: '\\\"\\\\uD80C\\\\u0000'\", json::parse_error&);\n CHECK_THROWS_WITH_AS(_ = json::parse(\"\\\"\\\\uD80C\\\\uFFFF\\\"\"),\n \"[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: '\\\"\\\\uD80C\\\\uFFFF'\", json::parse_error&);\n }\n\n SECTION(\"parse errors (accept)\")\n {\n // unexpected end of number\n CHECK(accept_helper(\"0.\") == false);\n CHECK(accept_helper(\"-\") == false);\n CHECK(accept_helper(\"--\") == false);\n CHECK(accept_helper(\"-0.\") == false);\n CHECK(accept_helper(\"-.\") == false);\n CHECK(accept_helper(\"-:\") == false);\n CHECK(accept_helper(\"0.:\") == false);\n CHECK(accept_helper(\"e.\") == false);\n CHECK(accept_helper(\"1e.\") == false);\n CHECK(accept_helper(\"1e/\") == false);\n CHECK(accept_helper(\"1e:\") == false);\n CHECK(accept_helper(\"1E.\") == false);\n CHECK(accept_helper(\"1E/\") == false);\n CHECK(accept_helper(\"1E:\") == false);\n\n // unexpected end of null\n CHECK(accept_helper(\"n\") == false);\n CHECK(accept_helper(\"nu\") == false);\n CHECK(accept_helper(\"nul\") == false);\n\n // unexpected end of true\n CHECK(accept_helper(\"t\") == false);\n CHECK(accept_helper(\"tr\") == false);\n CHECK(accept_helper(\"tru\") == false);\n\n // unexpected end of false\n CHECK(accept_helper(\"f\") == false);\n CHECK(accept_helper(\"fa\") == false);\n CHECK(accept_helper(\"fal\") == false);\n CHECK(accept_helper(\"fals\") == false);\n\n // missing/unexpected end of array\n CHECK(accept_helper(\"[\") == false);\n CHECK(accept_helper(\"[1\") == false);\n CHECK(accept_helper(\"[1,\") == false);\n CHECK(accept_helper(\"[1,]\") == false);\n CHECK(accept_helper(\"]\") == false);\n\n // missing/unexpected end of object\n CHECK(accept_helper(\"{\") == false);\n CHECK(accept_helper(\"{\\\"foo\\\"\") == false);\n CHECK(accept_helper(\"{\\\"foo\\\":\") == false);\n CHECK(accept_helper(\"{\\\"foo\\\":}\") == false);\n CHECK(accept_helper(\"{\\\"foo\\\":1,}\") == false);\n CHECK(accept_helper(\"}\") == false);\n\n // missing/unexpected end of string\n CHECK(accept_helper(\"\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\\\\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\\\u\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\\\u0\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\\\u01\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\\\u012\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\\\u\") == false);\n CHECK(accept_helper(\"\\\"\\\\u0\") == false);\n CHECK(accept_helper(\"\\\"\\\\u01\") == false);\n CHECK(accept_helper(\"\\\"\\\\u012\") == false);\n\n // unget of newline\n CHECK(parser_helper(\"\\n123\\n\") == 123);\n\n // invalid escapes\n for (int c = 1; c < 128; ++c)\n {\n auto s = std::string(\"\\\"\\\\\") + std::string(1, static_cast(c)) + \"\\\"\";\n\n switch (c)\n {\n // valid escapes\n case ('\"'):\n case ('\\\\'):\n case ('/'):\n case ('b'):\n case ('f'):\n case ('n'):\n case ('r'):\n case ('t'):\n {\n CHECK(json::parser(nlohmann::detail::input_adapter(s)).accept());\n break;\n }\n\n // \\u must be followed with four numbers, so we skip it here\n case ('u'):\n {\n break;\n }\n\n // any other combination of backslash and character is invalid\n default:\n {\n CHECK(json::parser(nlohmann::detail::input_adapter(s)).accept() == false);\n break;\n }\n }\n }\n\n // invalid \\uxxxx escapes\n {\n // check whether character is a valid hex character\n const auto valid = [](int c)\n {\n switch (c)\n {\n case ('0'):\n case ('1'):\n case ('2'):\n case ('3'):\n case ('4'):\n case ('5'):\n case ('6'):\n case ('7'):\n case ('8'):\n case ('9'):\n case ('a'):\n case ('b'):\n case ('c'):\n case ('d'):\n case ('e'):\n case ('f'):\n case ('A'):\n case ('B'):\n case ('C'):\n case ('D'):\n case ('E'):\n case ('F'):\n {\n return true;\n }\n\n default:\n {\n return false;\n }\n }\n };\n\n for (int c = 1; c < 128; ++c)\n {\n std::string const s = \"\\\"\\\\u\";\n\n // create a string with the iterated character at each position\n const auto s1 = s + \"000\" + std::string(1, static_cast(c)) + \"\\\"\";\n const auto s2 = s + \"00\" + std::string(1, static_cast(c)) + \"0\\\"\";\n const auto s3 = s + \"0\" + std::string(1, static_cast(c)) + \"00\\\"\";\n const auto s4 = s + std::string(1, static_cast(c)) + \"000\\\"\";\n\n if (valid(c))\n {\n CAPTURE(s1)\n CHECK(json::parser(nlohmann::detail::input_adapter(s1)).accept());\n CAPTURE(s2)\n CHECK(json::parser(nlohmann::detail::input_adapter(s2)).accept());\n CAPTURE(s3)\n CHECK(json::parser(nlohmann::detail::input_adapter(s3)).accept());\n CAPTURE(s4)\n CHECK(json::parser(nlohmann::detail::input_adapter(s4)).accept());\n }\n else\n {\n CAPTURE(s1)\n CHECK(json::parser(nlohmann::detail::input_adapter(s1)).accept() == false);\n\n CAPTURE(s2)\n CHECK(json::parser(nlohmann::detail::input_adapter(s2)).accept() == false);\n\n CAPTURE(s3)\n CHECK(json::parser(nlohmann::detail::input_adapter(s3)).accept() == false);\n\n CAPTURE(s4)\n CHECK(json::parser(nlohmann::detail::input_adapter(s4)).accept() == false);\n }\n }\n }\n\n // missing part of a surrogate pair\n CHECK(accept_helper(\"\\\"\\\\uD80C\\\"\") == false);\n // invalid surrogate pair\n CHECK(accept_helper(\"\\\"\\\\uD80C\\\\uD80C\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\\\uD80C\\\\u0000\\\"\") == false);\n CHECK(accept_helper(\"\\\"\\\\uD80C\\\\uFFFF\\\"\") == false);\n }\n\n SECTION(\"tests found by mutate++\")\n {\n // test case to make sure no comma precedes the first key\n CHECK_THROWS_WITH_AS(parser_helper(\"{,\\\"key\\\": false}\"), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing object key - unexpected ','; expected string literal\", json::parse_error&);\n // test case to make sure an object is properly closed\n CHECK_THROWS_WITH_AS(parser_helper(\"[{\\\"key\\\": false true]\"), \"[json.exception.parse_error.101] parse error at line 1, column 19: syntax error while parsing object - unexpected true literal; expected '}'\", json::parse_error&);\n\n // test case to make sure the callback is properly evaluated after reading a key\n {\n json::parser_callback_t const cb = [](int /*unused*/, json::parse_event_t event, json& /*unused*/) noexcept\n {\n return event != json::parse_event_t::key;\n };\n\n const json x = json::parse(\"{\\\"key\\\": false}\", cb);\n CHECK(x == json::object());\n }\n }\n\n SECTION(\"callback function\")\n {\n const auto* s_object = R\"(\n {\n \"foo\": 2,\n \"bar\": {\n \"baz\": 1\n }\n }\n )\";\n\n const auto* s_array = R\"(\n [1,2,[3,4,5],4,5]\n )\";\n\n const auto* structured_array = R\"(\n [\n 1,\n {\n \"foo\": \"bar\"\n },\n {\n \"qux\": \"baz\"\n }\n ]\n )\";\n\n const auto* structured_object = R\"(\n {\n \"foo\": [1, 2],\n \"bar\": 3\n }\n )\";\n\n SECTION(\"filter nothing\")\n {\n const json j_object = json::parse(s_object, [](int /*unused*/, json::parse_event_t /*unused*/, const json& /*unused*/) noexcept\n {\n return true;\n });\n\n CHECK (j_object == json({{\"foo\", 2}, {\"bar\", {{\"baz\", 1}}}}));\n\n const json j_array = json::parse(s_array, [](int /*unused*/, json::parse_event_t /*unused*/, const json& /*unused*/) noexcept\n {\n return true;\n });\n\n CHECK (j_array == json({1, 2, {3, 4, 5}, 4, 5}));\n }\n\n SECTION(\"filter everything\")\n {\n json const j_object = json::parse(s_object, [](int /*unused*/, json::parse_event_t /*unused*/, const json& /*unused*/) noexcept\n {\n return false;\n });\n\n // the top-level object will be discarded, leaving a null\n CHECK (j_object.is_null());\n\n json const j_array = json::parse(s_array, [](int /*unused*/, json::parse_event_t /*unused*/, const json& /*unused*/) noexcept\n {\n return false;\n });\n\n // the top-level array will be discarded, leaving a null\n CHECK (j_array.is_null());\n }\n\n SECTION(\"filter specific element\")\n {\n const json j_object = json::parse(s_object, [](int /*unused*/, json::parse_event_t event, const json & j) noexcept\n {\n // filter all number(2) elements\n return event != json::parse_event_t::value || j != json(2);\n });\n\n CHECK (j_object == json({{\"bar\", {{\"baz\", 1}}}}));\n\n const json j_array = json::parse(s_array, [](int /*unused*/, json::parse_event_t event, const json & j) noexcept\n {\n return event != json::parse_event_t::value || j != json(2);\n });\n\n CHECK (j_array == json({1, {3, 4, 5}, 4, 5}));\n }\n\n SECTION(\"filter object in array\")\n {\n const json j_filtered1 = json::parse(structured_array, [](int /*unused*/, json::parse_event_t e, const json & parsed)\n {\n return !(e == json::parse_event_t::object_end && parsed.contains(\"foo\"));\n });\n\n // the specified object will be discarded, and removed.\n CHECK (j_filtered1.size() == 2);\n CHECK (j_filtered1 == json({1, {{\"qux\", \"baz\"}}}));\n\n const json j_filtered2 = json::parse(structured_array, [](int /*unused*/, json::parse_event_t e, const json& /*parsed*/) noexcept\n {\n return e != json::parse_event_t::object_end;\n });\n\n // removed all objects in array.\n CHECK (j_filtered2.size() == 1);\n CHECK (j_filtered2 == json({1}));\n }\n\n SECTION(\"filter array in object\")\n {\n // the array is discarded once it is already stored under its key\n const json j_filtered1 = json::parse(structured_object, [](int /*unused*/, json::parse_event_t e, const json& /*parsed*/) noexcept\n {\n return e != json::parse_event_t::array_end;\n });\n\n CHECK (j_filtered1 == json({{\"bar\", 3}}));\n\n // the array is discarded before it is stored, leaving the\n // placeholder the key event wrote\n const json j_filtered2 = json::parse(structured_object, [](int /*unused*/, json::parse_event_t e, const json& /*parsed*/) noexcept\n {\n return e != json::parse_event_t::array_start;\n });\n\n CHECK (j_filtered2 == json({{\"bar\", 3}}));\n }\n\n SECTION(\"filter value in object\")\n {\n // the value is discarded after its key was kept, leaving the\n // placeholder the key event wrote\n const json j_filtered1 = json::parse(structured_object, [](int /*unused*/, json::parse_event_t e, const json & parsed) noexcept\n {\n return !(e == json::parse_event_t::value && parsed == json(3));\n });\n\n CHECK (j_filtered1 == json({{\"foo\", {1, 2}}}));\n\n // the same value is discarded together with its key, so no\n // placeholder was stored for it\n const json j_filtered2 = json::parse(structured_object, [](int /*unused*/, json::parse_event_t e, const json & parsed) noexcept\n {\n return !((e == json::parse_event_t::key && parsed == json(\"bar\")) ||\n (e == json::parse_event_t::value && parsed == json(3)));\n });\n\n CHECK (j_filtered2 == json({{\"foo\", {1, 2}}}));\n }\n\n SECTION(\"filter specific events\")\n {\n SECTION(\"first closing event\")\n {\n {\n const json j_object = json::parse(s_object, [](int /*unused*/, json::parse_event_t e, const json& /*unused*/) noexcept\n {\n static bool first = true;\n if (e == json::parse_event_t::object_end && first)\n {\n first = false;\n return false;\n }\n\n return true;\n });\n\n // the first completed object will be discarded\n CHECK (j_object == json({{\"foo\", 2}}));\n }\n\n {\n const json j_array = json::parse(s_array, [](int /*unused*/, json::parse_event_t e, const json& /*unused*/) noexcept\n {\n static bool first = true;\n if (e == json::parse_event_t::array_end && first)\n {\n first = false;\n return false;\n }\n\n return true;\n });\n\n // the first completed array will be discarded\n CHECK (j_array == json({1, 2, 4, 5}));\n }\n }\n }\n\n SECTION(\"special cases\")\n {\n // the following test cases cover the situation in which an empty\n // object and array is discarded only after the closing character\n // has been read\n\n const json j_empty_object = json::parse(\"{}\", [](int /*unused*/, json::parse_event_t e, const json& /*unused*/) noexcept\n {\n return e != json::parse_event_t::object_end;\n });\n CHECK(j_empty_object == json());\n\n const json j_empty_array = json::parse(\"[]\", [](int /*unused*/, json::parse_event_t e, const json& /*unused*/) noexcept\n {\n return e != json::parse_event_t::array_end;\n });\n CHECK(j_empty_array == json());\n }\n }\n\n SECTION(\"constructing from contiguous containers\")\n {\n SECTION(\"from std::vector\")\n {\n std::vector v = {'t', 'r', 'u', 'e'};\n json j;\n json::parser(nlohmann::detail::input_adapter(std::begin(v), std::end(v))).parse(true, j);\n CHECK(j == json(true));\n }\n\n SECTION(\"from std::array\")\n {\n std::array v { {'t', 'r', 'u', 'e'} };\n json j;\n json::parser(nlohmann::detail::input_adapter(std::begin(v), std::end(v))).parse(true, j);\n CHECK(j == json(true));\n }\n\n SECTION(\"from array\")\n {\n uint8_t v[] = {'t', 'r', 'u', 'e'}; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)\n json j;\n json::parser(nlohmann::detail::input_adapter(std::begin(v), std::end(v))).parse(true, j);\n CHECK(j == json(true));\n }\n\n SECTION(\"from char literal\")\n {\n CHECK(parser_helper(\"true\") == json(true));\n }\n\n SECTION(\"from std::string\")\n {\n std::string v = {'t', 'r', 'u', 'e'};\n json j;\n json::parser(nlohmann::detail::input_adapter(std::begin(v), std::end(v))).parse(true, j);\n CHECK(j == json(true));\n }\n\n SECTION(\"from std::initializer_list\")\n {\n std::initializer_list const v = {'t', 'r', 'u', 'e'};\n json j;\n json::parser(nlohmann::detail::input_adapter(std::begin(v), std::end(v))).parse(true, j);\n CHECK(j == json(true));\n }\n\n SECTION(\"from std::valarray\")\n {\n std::valarray v = {'t', 'r', 'u', 'e'};\n json j;\n json::parser(nlohmann::detail::input_adapter(std::begin(v), std::end(v))).parse(true, j);\n CHECK(j == json(true));\n }\n }\n\n SECTION(\"improve test coverage\")\n {\n SECTION(\"parser with callback\")\n {\n json::parser_callback_t const cb = [](int /*unused*/, json::parse_event_t /*unused*/, json& /*unused*/) noexcept\n {\n return true;\n };\n\n CHECK(json::parse(\"{\\\"foo\\\": true:\", cb, false).is_discarded());\n\n json _;\n CHECK_THROWS_WITH_AS(_ = json::parse(\"{\\\"foo\\\": true:\", cb), \"[json.exception.parse_error.101] parse error at line 1, column 13: syntax error while parsing object - unexpected ':'; expected '}'\", json::parse_error&);\n\n CHECK_THROWS_WITH_AS(_ = json::parse(\"1.18973e+4932\", cb), \"[json.exception.out_of_range.406] number overflow parsing '1.18973e+4932'\", json::out_of_range&);\n }\n\n SECTION(\"SAX parser\")\n {\n SECTION(\"} without value\")\n {\n SaxCountdown s(1);\n CHECK(json::sax_parse(\"{}\", &s) == false);\n }\n\n SECTION(\"} with value\")\n {\n SaxCountdown s(3);\n CHECK(json::sax_parse(\"{\\\"k1\\\": true}\", &s) == false);\n }\n\n SECTION(\"second key\")\n {\n SaxCountdown s(3);\n CHECK(json::sax_parse(\"{\\\"k1\\\": true, \\\"k2\\\": false}\", &s) == false);\n }\n\n SECTION(\"] without value\")\n {\n SaxCountdown s(1);\n CHECK(json::sax_parse(\"[]\", &s) == false);\n }\n\n SECTION(\"] with value\")\n {\n SaxCountdown s(2);\n CHECK(json::sax_parse(\"[1]\", &s) == false);\n }\n\n SECTION(\"float\")\n {\n SaxCountdown s(0);\n CHECK(json::sax_parse(\"3.14\", &s) == false);\n }\n\n SECTION(\"false\")\n {\n SaxCountdown s(0);\n CHECK(json::sax_parse(\"false\", &s) == false);\n }\n\n SECTION(\"null\")\n {\n SaxCountdown s(0);\n CHECK(json::sax_parse(\"null\", &s) == false);\n }\n\n SECTION(\"true\")\n {\n SaxCountdown s(0);\n CHECK(json::sax_parse(\"true\", &s) == false);\n }\n\n SECTION(\"unsigned\")\n {\n SaxCountdown s(0);\n CHECK(json::sax_parse(\"12\", &s) == false);\n }\n\n SECTION(\"integer\")\n {\n SaxCountdown s(0);\n CHECK(json::sax_parse(\"-12\", &s) == false);\n }\n\n SECTION(\"string\")\n {\n SaxCountdown s(0);\n CHECK(json::sax_parse(\"\\\"foo\\\"\", &s) == false);\n }\n }\n }\n\n SECTION(\"error messages for comments\")\n {\n json _;\n CHECK_THROWS_WITH_AS(_ = json::parse(\"/a\", nullptr, true, true), \"[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid comment; expecting '/' or '*' after '/'; last read: '/a'\", json::parse_error);\n CHECK_THROWS_WITH_AS(_ = json::parse(\"/*\", nullptr, true, true), \"[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid comment; missing closing '*/'; last read: '/*'\", json::parse_error);\n }\n}\n\n// this test relies on parse errors being thrown, so it is skipped when\n// exceptions are disabled (json::parse aborts instead of throwing there)\n#if !defined(JSON_NOEXCEPTION)\nnamespace\n{\n// Return the exception message from parsing @a input, or a \"\"\n// sentinel if the parse unexpectedly succeeds. json::parse is nodiscard, so the\n// result is consumed (via size()) to keep -Wunused-result / -Werror happy.\ntemplate\nstd::string parse_error_message(InputType&& input)\n{\n try\n {\n const json j = json::parse(std::forward(input));\n return \"\";\n }\n catch (const json::exception& e)\n {\n return e.what();\n }\n}\n\ntemplate\nstd::string parse_error_message_range(IteratorType first, IteratorType last)\n{\n try\n {\n const json j = json::parse(first, last);\n return \"\";\n }\n catch (const json::exception& e)\n {\n return e.what();\n }\n}\n} // namespace\n\nTEST_CASE(\"last-read diagnostics are identical across input adapters\")\n{\n // The lexer reconstructs the \"last read\" token lazily for seekable adapters\n // (contiguous byte input) and copies it eagerly for streaming adapters.\n // Both strategies must yield byte-for-byte identical error messages.\n\n // a selection of malformed inputs that exercise different token kinds,\n // whitespace/structural accumulation, number overflow, and control-char\n // escaping in the reconstructed \"last read\" token\n const std::vector inputs =\n {\n \"[1,2,x]\",\n \" \\n @\",\n \"{\\\"a\\\": }\",\n \"1.18973e+4932\",\n \"\\\"\\t\\\"\",\n \"tru\",\n \"[1 2]\",\n \"\\xEF\\xBB\\xBF nul\",\n };\n\n for (const auto& s : inputs)\n {\n CAPTURE(s);\n\n // reference: contiguous std::string -> seekable (lazy) path\n const std::string reference = parse_error_message(s);\n // every input is malformed, so parsing must fail (error messages start\n // with '['; the success sentinel returned above starts with '<')\n CHECK(reference.front() == '[');\n\n // const char* -> also seekable\n CHECK(parse_error_message(s.c_str()) == reference);\n\n // std::vector iterators -> seekable (random-access)\n {\n const std::vector v(s.begin(), s.end());\n CHECK(parse_error_message_range(v.begin(), v.end()) == reference);\n }\n\n // std::list iterators -> non-seekable (bidirectional) eager path\n {\n const std::list l(s.begin(), s.end());\n CHECK(parse_error_message_range(l.begin(), l.end()) == reference);\n }\n\n // std::istringstream -> non-seekable streaming eager path\n {\n std::istringstream ss(s);\n CHECK(parse_error_message(ss) == reference);\n }\n\n // wide strings -> wide_string_input_adapter eager path; only comparable\n // for ASCII input, as non-ASCII bytes are transcoded to different UTF-8\n const bool is_ascii = std::all_of(s.begin(), s.end(), [](char c)\n {\n return static_cast(c) < 0x80;\n });\n if (is_ascii)\n {\n const std::u16string w16(s.begin(), s.end());\n CHECK(parse_error_message(w16) == reference);\n\n const std::u32string w32(s.begin(), s.end());\n CHECK(parse_error_message(w32) == reference);\n }\n }\n}\n#endif // !defined(JSON_NOEXCEPTION)", "messages": null, "tools": null} {"id": "8884859476b12760", "category": "code", "domain": "code", "source": "ripgrep", "license": "MIT OR Unlicense", "license_url": "https://spdx.org/licenses/MIT.html", "path": "crates/ignore/src/pathutil.rs", "lang": "rust", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/BurntSushi/ripgrep", "commit": "3fce3b5bb0236da2df6d99672afb8a719642eca7", "collector": "tools/harvest.py"}, "chars": 4789, "sha256": "f339187002cb0ea893e8536fbfefcc50212b7383d71b27415e4de3eade2dba0b", "text": "use std::{ffi::OsStr, path::Path};\n\nuse crate::walk::DirEntry;\n\n/// Returns true if and only if this path is considered to be hidden.\n///\n/// # Platform behavior\n///\n/// ## Windows\n///\n/// This returns true if one of the following is true:\n///\n/// * The base name of the path starts with a `.`.\n/// * The file attributes have the `HIDDEN` property set.\n///\n/// ## All other platforms\n///\n/// This only returns true if the base name of the path starts with a `.`.\npub(crate) fn is_hidden_path(dent: &Path) -> bool {\n #[cfg(not(windows))]\n fn imp(path: &Path) -> bool {\n is_hidden_path_only(path)\n }\n\n #[cfg(windows)]\n fn imp(path: &Path) -> bool {\n use std::os::windows::fs::MetadataExt;\n use winapi_util::file;\n\n if let Ok(md) = path.metadata() {\n if file::is_hidden(md.file_attributes() as u64) {\n return true;\n }\n }\n is_hidden_path_only(path)\n }\n\n imp(dent)\n}\n\n/// Returns true if and only if this directory entry is considered to be\n/// hidden.\n///\n/// # Platform behavior\n///\n/// ## Windows\n///\n/// This returns true if one of the following is true:\n///\n/// * The base name of the path starts with a `.`.\n/// * The file attributes have the `HIDDEN` property set.\n///\n/// ## All other platforms\n///\n/// This only returns true if the base name of the path starts with a `.`.\npub(crate) fn is_hidden_entry(dent: &DirEntry) -> bool {\n #[cfg(not(windows))]\n fn imp(dent: &DirEntry) -> bool {\n is_hidden_path_only(dent.path())\n }\n\n #[cfg(windows)]\n fn imp(dent: &DirEntry) -> bool {\n use std::os::windows::fs::MetadataExt;\n use winapi_util::file;\n\n // This looks like we're doing an extra stat call, but on Windows, the\n // directory traverser reuses the metadata retrieved from each directory\n // entry and stores it on the DirEntry itself. So this is \"free.\"\n if let Ok(md) = dent.metadata() {\n if file::is_hidden(md.file_attributes() as u64) {\n return true;\n }\n }\n is_hidden_path_only(dent.path())\n }\n\n imp(dent)\n}\n\n/// Returns true if and only if this path is considered to be hidden from only\n/// the path itself.\n///\n/// This has the same behavior on all platforms.\nfn is_hidden_path_only(path: &Path) -> bool {\n if let Some(name) = file_name(path) {\n name.as_encoded_bytes().starts_with(b\".\")\n } else {\n false\n }\n}\n\n/// Strip `prefix` from the `path` and return the remainder.\n///\n/// If `path` doesn't have a prefix `prefix`, then return `None`.\npub(crate) fn strip_prefix<'a, P: AsRef + ?Sized>(\n prefix: &'a P,\n path: &'a Path,\n) -> Option<&'a Path> {\n #[cfg(unix)]\n fn imp<'a>(prefix: &'a Path, path: &'a Path) -> Option<&'a Path> {\n use std::os::unix::ffi::OsStrExt;\n\n let prefix = prefix.as_os_str().as_bytes();\n let path = path.as_os_str().as_bytes();\n if prefix.len() > path.len() || prefix != &path[0..prefix.len()] {\n None\n } else {\n Some(&Path::new(OsStr::from_bytes(&path[prefix.len()..])))\n }\n }\n\n #[cfg(not(unix))]\n fn imp<'a>(prefix: &'a Path, path: &'a Path) -> Option<&'a Path> {\n path.strip_prefix(prefix).ok()\n }\n\n imp(prefix.as_ref(), path)\n}\n\n/// Returns true if this file path is just a file name. i.e., Its parent is\n/// the empty string.\npub(crate) fn is_file_name>(path: P) -> bool {\n #[cfg(unix)]\n {\n memchr::memchr(b'/', path.as_ref().as_os_str().as_encoded_bytes())\n .is_none()\n }\n #[cfg(not(unix))]\n {\n path.as_ref()\n .parent()\n .map(|p| p.as_os_str().is_empty())\n .unwrap_or(false)\n }\n}\n\n/// The final component of the path, if it is a normal file.\n///\n/// If the path terminates in `.`, `..`, or consists solely of a root of\n/// prefix, this will return `None`.\npub(crate) fn file_name<'a, P: AsRef + ?Sized>(\n path: &'a P,\n) -> Option<&'a OsStr> {\n #[cfg(unix)]\n fn imp(path: &Path) -> Option<&OsStr> {\n use std::os::unix::ffi::OsStrExt;\n\n use memchr::memrchr;\n\n let path = path.as_os_str().as_bytes();\n if path.is_empty() {\n return None;\n } else if path.len() == 1 && path[0] == b'.' {\n return None;\n } else if path.last() == Some(&b'.') {\n return None;\n } else if path.len() >= 2 && &path[path.len() - 2..] == &b\"..\"[..] {\n return None;\n }\n let last_slash = memrchr(b'/', path).map(|i| i + 1).unwrap_or(0);\n Some(OsStr::from_bytes(&path[last_slash..]))\n }\n\n #[cfg(not(unix))]\n fn imp(path: &Path) -> Option<&OsStr> {\n path.file_name()\n }\n\n imp(path.as_ref())\n}", "messages": null, "tools": null} {"id": "88d4c3c300e413b0", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/api/adl_serializer/from_json.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 2223, "sha256": "5f83d75e003e4eb067819f1e33dbe723ec805cdb179b03e4faa0a23045668173", "text": "# nlohmann::adl_serializer::from_json\n\n```cpp\n// (1)\ntemplate\nstatic auto from_json(BasicJsonType && j, TargetType& val) noexcept(\n noexcept(::nlohmann::from_json(std::forward(j), val)))\n-> decltype(::nlohmann::from_json(std::forward(j), val), void())\n\n// (2)\ntemplate\nstatic auto from_json(BasicJsonType && j) noexcept(\nnoexcept(::nlohmann::from_json(std::forward(j), detail::identity_tag {})))\n-> decltype(::nlohmann::from_json(std::forward(j), detail::identity_tag {}))\n```\n\nThis function is usually called by the [`get()`](../basic_json/get.md) function of the [basic_json](../basic_json/index.md)\nclass (either explicitly or via the conversion operators).\n\n1. This function is chosen for default-constructible value types.\n2. This function is chosen for value types which are not default-constructible.\n\n## Parameters\n\n`j` (in)\n: JSON value to read from\n\n`val` (out)\n: value to write to\n\n## Return value\n\n1. (none) -- the converted value is written to the output parameter `val`.\n2. the JSON value `j` converted to `TargetType`\n\n## Examples\n\n??? example \"Example: (1) Default-constructible type\"\n\n The example below shows how a `from_json` function can be implemented for a user-defined type. This function is\n called by the `adl_serializer` when `get()` is called.\n \n ```cpp\n --8<-- \"examples/from_json__default_constructible.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/from_json__default_constructible.output\"\n ```\n\n??? example \"Example: (2) Non-default-constructible type\"\n\n The example below shows how a `from_json` is implemented as part of a specialization of the `adl_serializer` to\n realize the conversion of a non-default-constructible type.\n \n ```cpp\n --8<-- \"examples/from_json__non_default_constructible.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/from_json__non_default_constructible.output\"\n ```\n\n## See also\n\n- [to_json](to_json.md)\n\n## Version history\n\n- Added in version 2.1.0.", "messages": null, "tools": null} {"id": "892d692f1cb39c20", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/features/binary_formats/messagepack.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 7549, "sha256": "b4bfd3d206044576a5add6199f069898248e908b42fc8e0b169b8d45c1129f04", "text": "# MessagePack\n\nMessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON.\nBut it's faster and smaller. Small integers are encoded into a single byte, and typical short strings require only one\nextra byte in addition to the strings themselves.\n\n!!! abstract \"References\"\n\n - [MessagePack website](https://msgpack.org)\n - [MessagePack specification](https://github.com/msgpack/msgpack/blob/master/spec.md)\n\n## Serialization\n\nThe library uses the following mapping from JSON values types to MessagePack types according to the MessagePack\nspecification:\n\n| JSON value type | value/range | MessagePack type | first byte |\n|-----------------|------------------------------------------|------------------|------------|\n| null | `null` | nil | 0xC0 |\n| boolean | `true` | true | 0xC3 |\n| boolean | `false` | false | 0xC2 |\n| number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3 |\n| number_integer | -2147483648..-32769 | int32 | 0xD2 |\n| number_integer | -32768..-129 | int16 | 0xD1 |\n| number_integer | -128..-33 | int8 | 0xD0 |\n| number_integer | -32..-1 | negative fixint | 0xE0..0xFF |\n| number_integer | 0..127 | positive fixint | 0x00..0x7F |\n| number_integer | 128..255 | uint 8 | 0xCC |\n| number_integer | 256..65535 | uint 16 | 0xCD |\n| number_integer | 65536..4294967295 | uint 32 | 0xCE |\n| number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF |\n| number_unsigned | 0..127 | positive fixint | 0x00..0x7F |\n| number_unsigned | 128..255 | uint 8 | 0xCC |\n| number_unsigned | 256..65535 | uint 16 | 0xCD |\n| number_unsigned | 65536..4294967295 | uint 32 | 0xCE |\n| number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF |\n| number_float | *any value representable by a float* | float 32 | 0xCA |\n| number_float | *any value NOT representable by a float* | float 64 | 0xCB |\n| string | *length*: 0..31 | fixstr | 0xA0..0xBF |\n| string | *length*: 32..255 | str 8 | 0xD9 |\n| string | *length*: 256..65535 | str 16 | 0xDA |\n| string | *length*: 65536..4294967295 | str 32 | 0xDB |\n| array | *size*: 0..15 | fixarray | 0x90..0x9F |\n| array | *size*: 16..65535 | array 16 | 0xDC |\n| array | *size*: 65536..4294967295 | array 32 | 0xDD |\n| object | *size*: 0..15 | fix map | 0x80..0x8F |\n| object | *size*: 16..65535 | map 16 | 0xDE |\n| object | *size*: 65536..4294967295 | map 32 | 0xDF |\n| binary | *size*: 0..255 | bin 8 | 0xC4 |\n| binary | *size*: 256..65535 | bin 16 | 0xC5 |\n| binary | *size*: 65536..4294967295 | bin 32 | 0xC6 |\n\n!!! success \"Complete mapping\"\n\n The mapping is **complete** in the sense that any JSON value type can be converted to a MessagePack value.\n\n Any MessagePack output created by `to_msgpack` can be successfully parsed by `from_msgpack`.\n\n!!! warning \"Size constraints\"\n\n The following values can **not** be converted to a MessagePack value:\n\n - strings with more than 4294967295 bytes\n - byte strings with more than 4294967295 bytes\n - arrays with more than 4294967295 elements\n - objects with more than 4294967295 elements\n\n!!! info \"NaN/infinity handling\"\n\n `NaN`, `Infinity`, and `-Infinity` are serialized as a MessagePack float 32 (type 0xCA, 5 bytes total),\n regardless of magnitude, in contrast to the [dump](../../api/basic_json/dump.md) function which serializes NaN\n or Infinity to `null`.\n\n!!! note\n\n Prior to version 3.13.0, NaN and Infinity were instead serialized as a MessagePack float 64 (type 0xCB, 9 bytes\n total), because the check used to select the smaller float 32 encoding compared magnitudes with NaN, which is\n always `false` and caused the float 32 path to be skipped.\n\n??? example\n\n ```cpp\n --8<-- \"examples/to_msgpack.cpp\"\n ```\n \n Output:\n\n ```c\n --8<-- \"examples/to_msgpack.output\"\n ```\n\n## Deserialization\n\nThe library maps MessagePack types to JSON value types as follows:\n\n| MessagePack type | JSON value type | first byte |\n|------------------|-----------------|------------|\n| positive fixint | number_unsigned | 0x00..0x7F |\n| fixmap | object | 0x80..0x8F |\n| fixarray | array | 0x90..0x9F |\n| fixstr | string | 0xA0..0xBF |\n| nil | `null` | 0xC0 |\n| false | `false` | 0xC2 |\n| true | `true` | 0xC3 |\n| float 32 | number_float | 0xCA |\n| float 64 | number_float | 0xCB |\n| uint 8 | number_unsigned | 0xCC |\n| uint 16 | number_unsigned | 0xCD |\n| uint 32 | number_unsigned | 0xCE |\n| uint 64 | number_unsigned | 0xCF |\n| int 8 | number_integer | 0xD0 |\n| int 16 | number_integer | 0xD1 |\n| int 32 | number_integer | 0xD2 |\n| int 64 | number_integer | 0xD3 |\n| str 8 | string | 0xD9 |\n| str 16 | string | 0xDA |\n| str 32 | string | 0xDB |\n| array 16 | array | 0xDC |\n| array 32 | array | 0xDD |\n| map 16 | object | 0xDE |\n| map 32 | object | 0xDF |\n| bin 8 | binary | 0xC4 |\n| bin 16 | binary | 0xC5 |\n| bin 32 | binary | 0xC6 |\n| ext 8 | binary | 0xC7 |\n| ext 16 | binary | 0xC8 |\n| ext 32 | binary | 0xC9 |\n| fixext 1 | binary | 0xD4 |\n| fixext 2 | binary | 0xD5 |\n| fixext 4 | binary | 0xD6 |\n| fixext 8 | binary | 0xD7 |\n| fixext 16 | binary | 0xD8 |\n| negative fixint | number_integer | 0xE0-0xFF |\n\n!!! info\n\n Any MessagePack output created by `to_msgpack` can be successfully parsed by `from_msgpack`.\n\n\n??? example\n\n ```cpp\n --8<-- \"examples/from_msgpack.cpp\"\n ```\n\n Output:\n\n ```json\n --8<-- \"examples/from_msgpack.output\"\n ```", "messages": null, "tools": null} {"id": "8994746cd3467819", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/value__return_type.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 499, "sha256": "8267a36785df5101d86608039f566c6c28e4c25d42412690569c28c1fa84fdca", "text": "#include \n#include \n\nusing json = nlohmann::json;\n\nint main()\n{\n json j = json::parse(R\"({\"uint64\": 18446744073709551615})\");\n\n std::cout << \"operator[]: \" << j[\"uint64\"] << '\\n'\n << \"default value (int): \" << j.value(\"uint64\", 0) << '\\n'\n << \"default value (uint64_t): \" << j.value(\"uint64\", std::uint64_t(0)) << '\\n'\n << \"explicit return value type: \" << j.value(\"uint64\", 0) << '\\n';\n}", "messages": null, "tools": null} {"id": "8a28043e364d828c", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/hmr-full-bundle-mode/hmr-asset.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 291, "sha256": "2f549637e28c845743cf13d12c99349f468e0f20abd2ad8998ebdef739bd9e2e", "text": "// self-accepting module with no asset import; the spec adds one via an HMR edit\nconst slot = document.querySelector('.hmr-asset')\nconst img = document.createElement('img')\nimg.id = 'hmr-asset-image'\nimg.alt = 'hmr-asset'\nslot.replaceChildren(img)\n/* @asset-src */\n\nimport.meta.hot?.accept()", "messages": null, "tools": null} {"id": "8a9bc5c696379f7d", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/css-codesplit/shared-css-main.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 335, "sha256": "3f0a8d3ad4bffbc0dcfc4ec2150097767165ae4efbcbf211b4ec42a8f4a2b154", "text": "import shouldTreeshake from './shared-css-empty-2.js'\ndocument.querySelector('#app').innerHTML = `\n

\n

Shared CSS, with JS

\n
\n`\nfunction shouldBeTreeshaken_0() {\n // This function should be treeshaken, even if { moduleSideEffects: 'no-treeshake' }\n // was used in the JS corresponding to the HTML entrypoint.\n}", "messages": null, "tools": null} {"id": "8afc0a454bded954", "category": "code", "domain": "code", "source": "serde", "license": "MIT OR Apache-2.0", "license_url": "https://spdx.org/licenses/MIT.html", "path": "serde_derive/src/lib.rs", "lang": "rust", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/serde-rs/serde", "commit": "747814f7d5fbab872df3b02f070c165b91bde062", "collector": "tools/harvest.py"}, "chars": 3641, "sha256": "30a82c12e194913aa928f80cb0714d638b1c5ec7d7a314a07ec324a9d4495b3c", "text": "//! This crate provides Serde's two derive macros.\n//!\n//! ```edition2021\n//! # use serde_derive::{Deserialize, Serialize};\n//! #\n//! #[derive(Serialize, Deserialize)]\n//! # struct S;\n//! #\n//! # fn main() {}\n//! ```\n//!\n//! Please refer to [https://serde.rs/derive.html] for how to set this up.\n//!\n//! [https://serde.rs/derive.html]: https://serde.rs/derive.html\n\n#![doc(html_root_url = \"https://docs.rs/serde_derive/1.0.229\")]\n#![cfg_attr(not(check_cfg), allow(unexpected_cfgs))]\n// Ignored clippy lints\n#![allow(\n // clippy false positive: https://github.com/rust-lang/rust-clippy/issues/7054\n clippy::branches_sharing_code,\n clippy::cognitive_complexity,\n // clippy bug: https://github.com/rust-lang/rust-clippy/issues/7575\n clippy::collapsible_match,\n clippy::derive_partial_eq_without_eq,\n clippy::enum_variant_names,\n // clippy bug: https://github.com/rust-lang/rust-clippy/issues/6797\n clippy::manual_map,\n clippy::match_like_matches_macro,\n clippy::needless_lifetimes,\n clippy::needless_pass_by_value,\n clippy::too_many_arguments,\n clippy::trivially_copy_pass_by_ref,\n clippy::used_underscore_binding,\n clippy::wildcard_in_or_patterns,\n // clippy bug: https://github.com/rust-lang/rust-clippy/issues/5704\n clippy::unnested_or_patterns,\n)]\n// Ignored clippy_pedantic lints\n#![allow(\n clippy::cast_possible_truncation,\n clippy::checked_conversions,\n clippy::doc_markdown,\n clippy::elidable_lifetime_names,\n clippy::enum_glob_use,\n clippy::indexing_slicing,\n clippy::items_after_statements,\n clippy::let_underscore_untyped,\n clippy::manual_assert,\n clippy::map_err_ignore,\n clippy::match_same_arms,\n // clippy bug: https://github.com/rust-lang/rust-clippy/issues/6984\n clippy::match_wildcard_for_single_variants,\n clippy::module_name_repetitions,\n clippy::must_use_candidate,\n clippy::similar_names,\n clippy::single_match_else,\n clippy::struct_excessive_bools,\n clippy::too_many_lines,\n clippy::uninlined_format_args,\n clippy::unseparated_literal_suffix,\n clippy::unused_self,\n clippy::use_self,\n clippy::wildcard_imports\n)]\n#![cfg_attr(all(test, exhaustive), feature(non_exhaustive_omitted_patterns_lint))]\n#![allow(unknown_lints, mismatched_lifetime_syntaxes)]\n\nextern crate proc_macro2;\nextern crate quote;\nextern crate syn;\n\nextern crate proc_macro;\n\nmod internals;\n\nuse proc_macro::TokenStream;\nuse proc_macro2::{Ident, Span};\nuse quote::{ToTokens, TokenStreamExt as _};\nuse syn::parse_macro_input;\nuse syn::DeriveInput;\n\n#[macro_use]\nmod bound;\n#[macro_use]\nmod fragment;\n\nmod de;\nmod deprecated;\nmod dummy;\nmod pretend;\nmod ser;\nmod this;\n\n#[allow(non_camel_case_types)]\nstruct private;\n\nimpl private {\n fn ident(&self) -> Ident {\n Ident::new(\n concat!(\"__private\", env!(\"CARGO_PKG_VERSION_PATCH\")),\n Span::call_site(),\n )\n }\n}\n\nimpl ToTokens for private {\n fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {\n tokens.append(self.ident());\n }\n}\n\n#[proc_macro_derive(Serialize, attributes(serde))]\npub fn derive_serialize(input: TokenStream) -> TokenStream {\n let mut input = parse_macro_input!(input as DeriveInput);\n ser::expand_derive_serialize(&mut input)\n .unwrap_or_else(syn::Error::into_compile_error)\n .into()\n}\n\n#[proc_macro_derive(Deserialize, attributes(serde))]\npub fn derive_deserialize(input: TokenStream) -> TokenStream {\n let mut input = parse_macro_input!(input as DeriveInput);\n de::expand_derive_deserialize(&mut input)\n .unwrap_or_else(syn::Error::into_compile_error)\n .into()\n}", "messages": null, "tools": null} {"id": "8b0863604808df36", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/api/basic_json/find.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 2282, "sha256": "79a7f73c094462bc0d5688eedab736f2bb6cfee9e0aec393d546a2ce6e993054", "text": "# nlohmann::basic_json::find\n\n```cpp\n// (1)\niterator find(const typename object_t::key_type& key);\nconst_iterator find(const typename object_t::key_type& key) const;\n\n// (2)\ntemplate\niterator find(KeyType&& key);\ntemplate\nconst_iterator find(KeyType&& key) const;\n```\n\n1. Finds an element in a JSON object with a key equivalent to `key`. If the element is not found or the\n JSON value is not an object, `end()` is returned.\n2. See 1. This overload is only available if `KeyType` is comparable with `#!cpp typename object_t::key_type` and\n `#!cpp typename object_comparator_t::is_transparent` denotes a type.\n\n## Template parameters\n\n`KeyType`\n: A type for an object key other than [`json_pointer`](../json_pointer/index.md) that is comparable with\n [`string_t`](string_t.md) using [`object_comparator_t`](object_comparator_t.md).\n This can also be a string view (C++17).\n\n## Parameters\n\n`key` (in)\n: key value of the element to search for.\n \n## Return value\n\nIterator to an element with a key equivalent to `key`. If no such element is found or the JSON value is not an object,\na past-the-end iterator (see `end()`) is returned.\n\n## Exception safety\n\nStrong exception safety: if an exception occurs, the original value stays intact.\n\n## Complexity\n\nLogarithmic in the size of the JSON object.\n\n## Notes\n\nThis method always returns `end()` when executed on a JSON type that is not an object.\n\n## Examples\n\n??? example \"Example: (1) find object element by key\"\n\n The example shows how `find()` is used.\n \n ```cpp\n --8<-- \"examples/find__object_t_key_type.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/find__object_t_key_type.output\"\n ```\n\n??? example \"Example: (2) find object element by key using string_view\"\n\n The example shows how `find()` is used.\n \n ```cpp\n --8<-- \"examples/find__keytype.c++17.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/find__keytype.c++17.output\"\n ```\n\n## See also\n\n- [count](count.md) returns the number of occurrences of a key\n- [contains](contains.md) checks whether a key exists\n\n## Version history\n\n1. Added in version 3.11.0.\n2. Added in version 1.0.0. Changed to support comparable types in version 3.11.0.", "messages": null, "tools": null} {"id": "8b0a8df23a9eb85e", "category": "code", "domain": "code", "source": "serde", "license": "MIT OR Apache-2.0", "license_url": "https://spdx.org/licenses/MIT.html", "path": "serde_derive/src/ser.rs", "lang": "rust", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/serde-rs/serde", "commit": "747814f7d5fbab872df3b02f070c165b91bde062", "collector": "tools/harvest.py"}, "chars": 45067, "sha256": "d1166b312395224ff1663d94722a7d9b09b9003d214111b0d42cea60bca98147", "text": "use crate::de::field_i;\nuse crate::deprecated::allow_deprecated;\nuse crate::fragment::{Fragment, Match, Stmts};\nuse crate::internals::ast::{Container, Data, Field, Style, Variant};\nuse crate::internals::name::Name;\nuse crate::internals::{attr, replace_receiver, Ctxt, Derive};\nuse crate::{bound, dummy, pretend, private, this};\nuse proc_macro2::{Span, TokenStream};\nuse quote::{quote, quote_spanned};\nuse syn::spanned::Spanned;\nuse syn::{parse_quote, Ident, Index, Member};\n\npub fn expand_derive_serialize(input: &mut syn::DeriveInput) -> syn::Result {\n replace_receiver(input);\n\n let ctxt = Ctxt::new();\n let Some(cont) = Container::from_ast(&ctxt, input, Derive::Serialize, &private.ident()) else {\n return Err(ctxt.check().unwrap_err());\n };\n precondition(&ctxt, &cont);\n ctxt.check()?;\n\n let ident = &cont.ident;\n let params = Parameters::new(&cont);\n let (impl_generics, ty_generics, where_clause) = params.generics.split_for_impl();\n let body = Stmts(serialize_body(&cont, ¶ms));\n let allow_deprecated = allow_deprecated(input);\n\n let impl_block = if let Some(remote) = cont.attrs.remote() {\n let vis = &input.vis;\n let used = pretend::pretend_used(&cont, params.is_packed);\n quote! {\n #[automatically_derived]\n #allow_deprecated\n impl #impl_generics #ident #ty_generics #where_clause {\n #vis fn serialize<__S>(__self: &#remote #ty_generics, __serializer: __S) -> _serde::#private::Result<__S::Ok, __S::Error>\n where\n __S: _serde::Serializer,\n {\n #used\n #body\n }\n }\n }\n } else {\n quote! {\n #[automatically_derived]\n #allow_deprecated\n impl #impl_generics _serde::Serialize for #ident #ty_generics #where_clause {\n fn serialize<__S>(&self, __serializer: __S) -> _serde::#private::Result<__S::Ok, __S::Error>\n where\n __S: _serde::Serializer,\n {\n #body\n }\n }\n }\n };\n\n Ok(dummy::wrap_in_const(\n cont.attrs.custom_serde_path(),\n impl_block,\n ))\n}\n\nfn precondition(cx: &Ctxt, cont: &Container) {\n match cont.attrs.identifier() {\n attr::Identifier::No => {}\n attr::Identifier::Field => {\n cx.error_spanned_by(cont.original, \"field identifiers cannot be serialized\");\n }\n attr::Identifier::Variant => {\n cx.error_spanned_by(cont.original, \"variant identifiers cannot be serialized\");\n }\n }\n}\n\nstruct Parameters {\n /// Variable holding the value being serialized. Either `self` for local\n /// types or `__self` for remote types.\n self_var: Ident,\n\n /// Path to the type the impl is for. Either a single `Ident` for local\n /// types (does not include generic parameters) or `some::remote::Path` for\n /// remote types.\n this_type: syn::Path,\n\n /// Same as `this_type` but using `::` for generic parameters for use in\n /// expression position.\n this_value: syn::Path,\n\n /// Generics including any explicit and inferred bounds for the impl.\n generics: syn::Generics,\n\n /// Type has a `serde(remote = \"...\")` attribute.\n is_remote: bool,\n\n /// Type has a repr(packed) attribute.\n is_packed: bool,\n}\n\nimpl Parameters {\n fn new(cont: &Container) -> Self {\n let is_remote = cont.attrs.remote().is_some();\n let self_var = if is_remote {\n Ident::new(\"__self\", Span::call_site())\n } else {\n Ident::new(\"self\", Span::call_site())\n };\n\n let this_type = this::this_type(cont);\n let this_value = this::this_value(cont);\n let is_packed = cont.attrs.is_packed();\n let generics = build_generics(cont);\n\n Parameters {\n self_var,\n this_type,\n this_value,\n generics,\n is_remote,\n is_packed,\n }\n }\n\n /// Type name to use in error messages and `&'static str` arguments to\n /// various Serializer methods.\n fn type_name(&self) -> String {\n self.this_type.segments.last().unwrap().ident.to_string()\n }\n}\n\n// All the generics in the input, plus a bound `T: Serialize` for each generic\n// field type that will be serialized by us.\nfn build_generics(cont: &Container) -> syn::Generics {\n let generics = bound::without_defaults(cont.generics);\n\n let generics =\n bound::with_where_predicates_from_fields(cont, &generics, attr::Field::ser_bound);\n\n let generics =\n bound::with_where_predicates_from_variants(cont, &generics, attr::Variant::ser_bound);\n\n match cont.attrs.ser_bound() {\n Some(predicates) => bound::with_where_predicates(&generics, predicates),\n None => bound::with_bound(\n cont,\n &generics,\n needs_serialize_bound,\n &parse_quote!(_serde::Serialize),\n ),\n }\n}\n\n// Fields with a `skip_serializing` or `serialize_with` attribute, or which\n// belong to a variant with a `skip_serializing` or `serialize_with` attribute,\n// are not serialized by us so we do not generate a bound. Fields with a `bound`\n// attribute specify their own bound so we do not generate one. All other fields\n// may need a `T: Serialize` bound where T is the type of the field.\nfn needs_serialize_bound(field: &attr::Field, variant: Option<&attr::Variant>) -> bool {\n !field.skip_serializing()\n && field.serialize_with().is_none()\n && field.ser_bound().is_none()\n && variant.map_or(true, |variant| {\n !variant.skip_serializing()\n && variant.serialize_with().is_none()\n && variant.ser_bound().is_none()\n })\n}\n\nfn serialize_body(cont: &Container, params: &Parameters) -> Fragment {\n if cont.attrs.transparent() {\n serialize_transparent(cont, params)\n } else if let Some(type_into) = cont.attrs.type_into() {\n serialize_into(params, type_into)\n } else {\n match &cont.data {\n Data::Enum(variants) => serialize_enum(params, variants, &cont.attrs),\n Data::Struct(Style::Struct, fields) => serialize_struct(params, fields, &cont.attrs),\n Data::Struct(Style::Tuple, fields) => {\n serialize_tuple_struct(params, fields, &cont.attrs)\n }\n Data::Struct(Style::Newtype, fields) => {\n serialize_newtype_struct(params, &fields[0], &cont.attrs)\n }\n Data::Struct(Style::Unit, _) => serialize_unit_struct(&cont.attrs),\n }\n }\n}\n\nfn serialize_transparent(cont: &Container, params: &Parameters) -> Fragment {\n let fields = match &cont.data {\n Data::Struct(_, fields) => fields,\n Data::Enum(_) => unreachable!(),\n };\n\n let self_var = ¶ms.self_var;\n let transparent_field = fields.iter().find(|f| f.attrs.transparent()).unwrap();\n let member = &transparent_field.member;\n\n let path = match transparent_field.attrs.serialize_with() {\n Some(path) => quote!(#path),\n None => {\n let span = transparent_field.original.span();\n quote_spanned!(span=> _serde::Serialize::serialize)\n }\n };\n\n quote_block! {\n #path(&#self_var.#member, __serializer)\n }\n}\n\nfn serialize_into(params: &Parameters, type_into: &syn::Type) -> Fragment {\n let self_var = ¶ms.self_var;\n quote_block! {\n _serde::Serialize::serialize(\n &_serde::#private::Into::<#type_into>::into(_serde::#private::Clone::clone(#self_var)),\n __serializer)\n }\n}\n\nfn serialize_unit_struct(cattrs: &attr::Container) -> Fragment {\n let type_name = cattrs.name().serialize_name();\n\n quote_expr! {\n _serde::Serializer::serialize_unit_struct(__serializer, #type_name)\n }\n}\n\nfn serialize_newtype_struct(\n params: &Parameters,\n field: &Field,\n cattrs: &attr::Container,\n) -> Fragment {\n let type_name = cattrs.name().serialize_name();\n\n let mut field_expr = get_member(\n params,\n field,\n &Member::Unnamed(Index {\n index: 0,\n span: Span::call_site(),\n }),\n );\n if let Some(path) = field.attrs.serialize_with() {\n field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr);\n }\n\n let span = field.original.span();\n let func = quote_spanned!(span=> _serde::Serializer::serialize_newtype_struct);\n quote_expr! {\n #func(__serializer, #type_name, #field_expr)\n }\n}\n\nfn serialize_tuple_struct(\n params: &Parameters,\n fields: &[Field],\n cattrs: &attr::Container,\n) -> Fragment {\n let serialize_stmts =\n serialize_tuple_struct_visitor(fields, params, false, &TupleTrait::SerializeTupleStruct);\n\n let type_name = cattrs.name().serialize_name();\n\n let mut serialized_fields = fields\n .iter()\n .enumerate()\n .filter(|(_, field)| !field.attrs.skip_serializing())\n .peekable();\n\n let let_mut = mut_if(serialized_fields.peek().is_some());\n\n let len = serialized_fields\n .map(|(i, field)| match field.attrs.skip_serializing_if() {\n None => quote!(1),\n Some(path) => {\n let index = syn::Index {\n index: i as u32,\n span: Span::call_site(),\n };\n let field_expr = get_member(params, field, &Member::Unnamed(index));\n quote!(if #path(#field_expr) { 0 } else { 1 })\n }\n })\n .fold(quote!(0), |sum, expr| quote!(#sum + #expr));\n\n quote_block! {\n let #let_mut __serde_state = _serde::Serializer::serialize_tuple_struct(__serializer, #type_name, #len)?;\n #(#serialize_stmts)*\n _serde::ser::SerializeTupleStruct::end(__serde_state)\n }\n}\n\nfn serialize_struct(params: &Parameters, fields: &[Field], cattrs: &attr::Container) -> Fragment {\n assert!(\n fields.len() as u64 <= u64::from(u32::MAX),\n \"too many fields in {}: {}, maximum supported count is {}\",\n cattrs.name().serialize_name(),\n fields.len(),\n u32::MAX,\n );\n\n let has_non_skipped_flatten = fields\n .iter()\n .any(|field| field.attrs.flatten() && !field.attrs.skip_serializing());\n if has_non_skipped_flatten {\n serialize_struct_as_map(params, fields, cattrs)\n } else {\n serialize_struct_as_struct(params, fields, cattrs)\n }\n}\n\nfn serialize_struct_tag_field(cattrs: &attr::Container, struct_trait: &StructTrait) -> TokenStream {\n match cattrs.tag() {\n attr::TagType::Internal { tag } => {\n let type_name = cattrs.name().serialize_name();\n let func = struct_trait.serialize_field(Span::call_site());\n quote! {\n #func(&mut __serde_state, #tag, #type_name)?;\n }\n }\n _ => quote! {},\n }\n}\n\nfn serialize_struct_as_struct(\n params: &Parameters,\n fields: &[Field],\n cattrs: &attr::Container,\n) -> Fragment {\n let serialize_fields =\n serialize_struct_visitor(fields, params, false, &StructTrait::SerializeStruct);\n\n let type_name = cattrs.name().serialize_name();\n\n let tag_field = serialize_struct_tag_field(cattrs, &StructTrait::SerializeStruct);\n let tag_field_exists = !tag_field.is_empty();\n\n let mut serialized_fields = fields\n .iter()\n .filter(|&field| !field.attrs.skip_serializing())\n .peekable();\n\n let let_mut = mut_if(serialized_fields.peek().is_some() || tag_field_exists);\n\n let len = serialized_fields\n .map(|field| match field.attrs.skip_serializing_if() {\n None => quote!(1),\n Some(path) => {\n let field_expr = get_member(params, field, &field.member);\n quote!(if #path(#field_expr) { 0 } else { 1 })\n }\n })\n .fold(\n quote!(#tag_field_exists as usize),\n |sum, expr| quote!(#sum + #expr),\n );\n\n quote_block! {\n let #let_mut __serde_state = _serde::Serializer::serialize_struct(__serializer, #type_name, #len)?;\n #tag_field\n #(#serialize_fields)*\n _serde::ser::SerializeStruct::end(__serde_state)\n }\n}\n\nfn serialize_struct_as_map(\n params: &Parameters,\n fields: &[Field],\n cattrs: &attr::Container,\n) -> Fragment {\n let serialize_fields =\n serialize_struct_visitor(fields, params, false, &StructTrait::SerializeMap);\n\n let tag_field = serialize_struct_tag_field(cattrs, &StructTrait::SerializeMap);\n let tag_field_exists = !tag_field.is_empty();\n\n let mut serialized_fields = fields\n .iter()\n .filter(|&field| !field.attrs.skip_serializing())\n .peekable();\n\n let let_mut = mut_if(serialized_fields.peek().is_some() || tag_field_exists);\n\n quote_block! {\n let #let_mut __serde_state = _serde::Serializer::serialize_map(__serializer, _serde::#private::None)?;\n #tag_field\n #(#serialize_fields)*\n _serde::ser::SerializeMap::end(__serde_state)\n }\n}\n\nfn serialize_enum(params: &Parameters, variants: &[Variant], cattrs: &attr::Container) -> Fragment {\n assert!(variants.len() as u64 <= u64::from(u32::MAX));\n\n let self_var = ¶ms.self_var;\n\n let mut arms: Vec<_> = variants\n .iter()\n .enumerate()\n .map(|(variant_index, variant)| {\n serialize_variant(params, variant, variant_index as u32, cattrs)\n })\n .collect();\n\n if cattrs.remote().is_some() && cattrs.non_exhaustive() {\n arms.push(quote! {\n ref unrecognized => _serde::#private::Err(_serde::ser::Error::custom(_serde::#private::ser::CannotSerializeVariant(unrecognized))),\n });\n }\n\n quote_expr! {\n match *#self_var {\n #(#arms)*\n }\n }\n}\n\nfn serialize_variant(\n params: &Parameters,\n variant: &Variant,\n variant_index: u32,\n cattrs: &attr::Container,\n) -> TokenStream {\n let this_value = ¶ms.this_value;\n let variant_ident = &variant.ident;\n\n if variant.attrs.skip_serializing() {\n let skipped_msg = format!(\n \"the enum variant {}::{} cannot be serialized\",\n params.type_name(),\n variant_ident\n );\n let skipped_err = quote! {\n _serde::#private::Err(_serde::ser::Error::custom(#skipped_msg))\n };\n let fields_pat = match variant.style {\n Style::Unit => quote!(),\n Style::Newtype | Style::Tuple => quote!((..)),\n Style::Struct => quote!({ .. }),\n };\n quote! {\n #this_value::#variant_ident #fields_pat => #skipped_err,\n }\n } else {\n // variant wasn't skipped\n let case = match variant.style {\n Style::Unit => {\n quote! {\n #this_value::#variant_ident\n }\n }\n Style::Newtype => {\n quote! {\n #this_value::#variant_ident(ref __field0)\n }\n }\n Style::Tuple => {\n let field_names = (0..variant.fields.len()).map(field_i);\n quote! {\n #this_value::#variant_ident(#(ref #field_names),*)\n }\n }\n Style::Struct => {\n let members = variant.fields.iter().map(|f| &f.member);\n quote! {\n #this_value::#variant_ident { #(ref #members),* }\n }\n }\n };\n\n let body = Match(match (cattrs.tag(), variant.attrs.untagged()) {\n (attr::TagType::External, false) => {\n serialize_externally_tagged_variant(params, variant, variant_index, cattrs)\n }\n (attr::TagType::Internal { tag }, false) => {\n serialize_internally_tagged_variant(params, variant, cattrs, tag)\n }\n (attr::TagType::Adjacent { tag, content }, false) => {\n serialize_adjacently_tagged_variant(\n params,\n variant,\n cattrs,\n variant_index,\n tag,\n content,\n )\n }\n (attr::TagType::None, _) | (_, true) => {\n serialize_untagged_variant(params, variant, cattrs)\n }\n });\n\n quote! {\n #case => #body\n }\n }\n}\n\nfn serialize_externally_tagged_variant(\n params: &Parameters,\n variant: &Variant,\n variant_index: u32,\n cattrs: &attr::Container,\n) -> Fragment {\n let type_name = cattrs.name().serialize_name();\n let variant_name = variant.attrs.name().serialize_name();\n\n if let Some(path) = variant.attrs.serialize_with() {\n let ser = wrap_serialize_variant_with(params, path, variant);\n return quote_expr! {\n _serde::Serializer::serialize_newtype_variant(\n __serializer,\n #type_name,\n #variant_index,\n #variant_name,\n #ser,\n )\n };\n }\n\n match effective_style(variant) {\n Style::Unit => {\n quote_expr! {\n _serde::Serializer::serialize_unit_variant(\n __serializer,\n #type_name,\n #variant_index,\n #variant_name,\n )\n }\n }\n Style::Newtype => {\n let field = &variant.fields[0];\n let mut field_expr = quote!(__field0);\n if let Some(path) = field.attrs.serialize_with() {\n field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr);\n }\n\n let span = field.original.span();\n let func = quote_spanned!(span=> _serde::Serializer::serialize_newtype_variant);\n quote_expr! {\n #func(\n __serializer,\n #type_name,\n #variant_index,\n #variant_name,\n #field_expr,\n )\n }\n }\n Style::Tuple => serialize_tuple_variant(\n TupleVariant::ExternallyTagged {\n type_name,\n variant_index,\n variant_name,\n },\n params,\n &variant.fields,\n ),\n Style::Struct => serialize_struct_variant(\n StructVariant::ExternallyTagged {\n variant_index,\n variant_name,\n },\n params,\n &variant.fields,\n type_name,\n ),\n }\n}\n\nfn serialize_internally_tagged_variant(\n params: &Parameters,\n variant: &Variant,\n cattrs: &attr::Container,\n tag: &str,\n) -> Fragment {\n let type_name = cattrs.name().serialize_name();\n let variant_name = variant.attrs.name().serialize_name();\n\n let enum_ident_str = params.type_name();\n let variant_ident_str = variant.ident.to_string();\n\n if let Some(path) = variant.attrs.serialize_with() {\n let ser = wrap_serialize_variant_with(params, path, variant);\n return quote_expr! {\n _serde::#private::ser::serialize_tagged_newtype(\n __serializer,\n #enum_ident_str,\n #variant_ident_str,\n #tag,\n #variant_name,\n #ser,\n )\n };\n }\n\n match effective_style(variant) {\n Style::Unit => {\n quote_block! {\n let mut __struct = _serde::Serializer::serialize_struct(\n __serializer, #type_name, 1)?;\n _serde::ser::SerializeStruct::serialize_field(\n &mut __struct, #tag, #variant_name)?;\n _serde::ser::SerializeStruct::end(__struct)\n }\n }\n Style::Newtype => {\n let field = &variant.fields[0];\n let mut field_expr = quote!(__field0);\n if let Some(path) = field.attrs.serialize_with() {\n field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr);\n }\n\n let span = field.original.span();\n let func = quote_spanned!(span=> _serde::#private::ser::serialize_tagged_newtype);\n quote_expr! {\n #func(\n __serializer,\n #enum_ident_str,\n #variant_ident_str,\n #tag,\n #variant_name,\n #field_expr,\n )\n }\n }\n Style::Struct => serialize_struct_variant(\n StructVariant::InternallyTagged { tag, variant_name },\n params,\n &variant.fields,\n type_name,\n ),\n Style::Tuple => unreachable!(\"checked in serde_derive_internals\"),\n }\n}\n\nfn serialize_adjacently_tagged_variant(\n params: &Parameters,\n variant: &Variant,\n cattrs: &attr::Container,\n variant_index: u32,\n tag: &str,\n content: &str,\n) -> Fragment {\n let this_type = ¶ms.this_type;\n let type_name = cattrs.name().serialize_name();\n let variant_name = variant.attrs.name().serialize_name();\n let serialize_variant = quote! {\n &_serde::#private::ser::AdjacentlyTaggedEnumVariant {\n enum_name: #type_name,\n variant_index: #variant_index,\n variant_name: #variant_name,\n }\n };\n\n let inner = Stmts(if let Some(path) = variant.attrs.serialize_with() {\n let ser = wrap_serialize_variant_with(params, path, variant);\n quote_expr! {\n _serde::Serialize::serialize(#ser, __serializer)\n }\n } else {\n match effective_style(variant) {\n Style::Unit => {\n return quote_block! {\n let mut __struct = _serde::Serializer::serialize_struct(\n __serializer, #type_name, 1)?;\n _serde::ser::SerializeStruct::serialize_field(\n &mut __struct, #tag, #serialize_variant)?;\n _serde::ser::SerializeStruct::end(__struct)\n };\n }\n Style::Newtype => {\n let field = &variant.fields[0];\n let mut field_expr = quote!(__field0);\n if let Some(path) = field.attrs.serialize_with() {\n field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr);\n }\n\n let span = field.original.span();\n let func = quote_spanned!(span=> _serde::ser::SerializeStruct::serialize_field);\n return quote_block! {\n let mut __struct = _serde::Serializer::serialize_struct(\n __serializer, #type_name, 2)?;\n _serde::ser::SerializeStruct::serialize_field(\n &mut __struct, #tag, #serialize_variant)?;\n #func(\n &mut __struct, #content, #field_expr)?;\n _serde::ser::SerializeStruct::end(__struct)\n };\n }\n Style::Tuple => {\n serialize_tuple_variant(TupleVariant::Untagged, params, &variant.fields)\n }\n Style::Struct => serialize_struct_variant(\n StructVariant::Untagged,\n params,\n &variant.fields,\n variant_name,\n ),\n }\n });\n\n let fields_ty = variant.fields.iter().map(|f| &f.ty);\n let fields_ident: &[_] = &match variant.style {\n Style::Unit => {\n if variant.attrs.serialize_with().is_some() {\n vec![]\n } else {\n unreachable!()\n }\n }\n Style::Newtype => vec![Member::Named(field_i(0))],\n Style::Tuple => (0..variant.fields.len())\n .map(|i| Member::Named(field_i(i)))\n .collect(),\n Style::Struct => variant.fields.iter().map(|f| f.member.clone()).collect(),\n };\n\n let (_, ty_generics, where_clause) = params.generics.split_for_impl();\n\n let wrapper_generics = if fields_ident.is_empty() {\n params.generics.clone()\n } else {\n bound::with_lifetime_bound(¶ms.generics, \"'__a\")\n };\n let (wrapper_impl_generics, wrapper_ty_generics, _) = wrapper_generics.split_for_impl();\n\n quote_block! {\n #[doc(hidden)]\n struct __AdjacentlyTagged #wrapper_generics #where_clause {\n data: (#(&'__a #fields_ty,)*),\n phantom: _serde::#private::PhantomData<#this_type #ty_generics>,\n }\n\n #[automatically_derived]\n impl #wrapper_impl_generics _serde::Serialize for __AdjacentlyTagged #wrapper_ty_generics #where_clause {\n fn serialize<__S>(&self, __serializer: __S) -> _serde::#private::Result<__S::Ok, __S::Error>\n where\n __S: _serde::Serializer,\n {\n // Elements that have skip_serializing will be unused.\n #[allow(unused_variables)]\n let (#(#fields_ident,)*) = self.data;\n #inner\n }\n }\n\n let mut __struct = _serde::Serializer::serialize_struct(\n __serializer, #type_name, 2)?;\n _serde::ser::SerializeStruct::serialize_field(\n &mut __struct, #tag, #serialize_variant)?;\n _serde::ser::SerializeStruct::serialize_field(\n &mut __struct, #content, &__AdjacentlyTagged {\n data: (#(#fields_ident,)*),\n phantom: _serde::#private::PhantomData::<#this_type #ty_generics>,\n })?;\n _serde::ser::SerializeStruct::end(__struct)\n }\n}\n\nfn serialize_untagged_variant(\n params: &Parameters,\n variant: &Variant,\n cattrs: &attr::Container,\n) -> Fragment {\n if let Some(path) = variant.attrs.serialize_with() {\n let ser = wrap_serialize_variant_with(params, path, variant);\n return quote_expr! {\n _serde::Serialize::serialize(#ser, __serializer)\n };\n }\n\n match effective_style(variant) {\n Style::Unit => {\n quote_expr! {\n _serde::Serializer::serialize_unit(__serializer)\n }\n }\n Style::Newtype => {\n let field = &variant.fields[0];\n let mut field_expr = quote!(__field0);\n if let Some(path) = field.attrs.serialize_with() {\n field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr);\n }\n\n let span = field.original.span();\n let func = quote_spanned!(span=> _serde::Serialize::serialize);\n quote_expr! {\n #func(#field_expr, __serializer)\n }\n }\n Style::Tuple => serialize_tuple_variant(TupleVariant::Untagged, params, &variant.fields),\n Style::Struct => {\n let type_name = cattrs.name().serialize_name();\n serialize_struct_variant(StructVariant::Untagged, params, &variant.fields, type_name)\n }\n }\n}\n\nenum TupleVariant<'a> {\n ExternallyTagged {\n type_name: &'a Name,\n variant_index: u32,\n variant_name: &'a Name,\n },\n Untagged,\n}\n\nfn serialize_tuple_variant(\n context: TupleVariant,\n params: &Parameters,\n fields: &[Field],\n) -> Fragment {\n let tuple_trait = match context {\n TupleVariant::ExternallyTagged { .. } => TupleTrait::SerializeTupleVariant,\n TupleVariant::Untagged => TupleTrait::SerializeTuple,\n };\n\n let serialize_stmts = serialize_tuple_struct_visitor(fields, params, true, &tuple_trait);\n\n let mut serialized_fields = fields\n .iter()\n .enumerate()\n .filter(|(_, field)| !field.attrs.skip_serializing())\n .peekable();\n\n let let_mut = mut_if(serialized_fields.peek().is_some());\n\n let len = serialized_fields\n .map(|(i, field)| match field.attrs.skip_serializing_if() {\n None => quote!(1),\n Some(path) => {\n let field_expr = field_i(i);\n quote!(if #path(#field_expr) { 0 } else { 1 })\n }\n })\n .fold(quote!(0), |sum, expr| quote!(#sum + #expr));\n\n match context {\n TupleVariant::ExternallyTagged {\n type_name,\n variant_index,\n variant_name,\n } => {\n quote_block! {\n let #let_mut __serde_state = _serde::Serializer::serialize_tuple_variant(\n __serializer,\n #type_name,\n #variant_index,\n #variant_name,\n #len)?;\n #(#serialize_stmts)*\n _serde::ser::SerializeTupleVariant::end(__serde_state)\n }\n }\n TupleVariant::Untagged => {\n quote_block! {\n let #let_mut __serde_state = _serde::Serializer::serialize_tuple(\n __serializer,\n #len)?;\n #(#serialize_stmts)*\n _serde::ser::SerializeTuple::end(__serde_state)\n }\n }\n }\n}\n\nenum StructVariant<'a> {\n ExternallyTagged {\n variant_index: u32,\n variant_name: &'a Name,\n },\n InternallyTagged {\n tag: &'a str,\n variant_name: &'a Name,\n },\n Untagged,\n}\n\nfn serialize_struct_variant(\n context: StructVariant,\n params: &Parameters,\n fields: &[Field],\n name: &Name,\n) -> Fragment {\n if fields.iter().any(|field| field.attrs.flatten()) {\n return serialize_struct_variant_with_flatten(context, params, fields, name);\n }\n\n let struct_trait = match context {\n StructVariant::ExternallyTagged { .. } => StructTrait::SerializeStructVariant,\n StructVariant::InternallyTagged { .. } | StructVariant::Untagged => {\n StructTrait::SerializeStruct\n }\n };\n\n let serialize_fields = serialize_struct_visitor(fields, params, true, &struct_trait);\n\n let mut serialized_fields = fields\n .iter()\n .filter(|&field| !field.attrs.skip_serializing())\n .peekable();\n\n let let_mut = mut_if(serialized_fields.peek().is_some());\n\n let len = serialized_fields\n .map(|field| {\n let member = &field.member;\n\n match field.attrs.skip_serializing_if() {\n Some(path) => quote!(if #path(#member) { 0 } else { 1 }),\n None => quote!(1),\n }\n })\n .fold(quote!(0), |sum, expr| quote!(#sum + #expr));\n\n match context {\n StructVariant::ExternallyTagged {\n variant_index,\n variant_name,\n } => {\n quote_block! {\n let #let_mut __serde_state = _serde::Serializer::serialize_struct_variant(\n __serializer,\n #name,\n #variant_index,\n #variant_name,\n #len,\n )?;\n #(#serialize_fields)*\n _serde::ser::SerializeStructVariant::end(__serde_state)\n }\n }\n StructVariant::InternallyTagged { tag, variant_name } => {\n quote_block! {\n let mut __serde_state = _serde::Serializer::serialize_struct(\n __serializer,\n #name,\n #len + 1,\n )?;\n _serde::ser::SerializeStruct::serialize_field(\n &mut __serde_state,\n #tag,\n #variant_name,\n )?;\n #(#serialize_fields)*\n _serde::ser::SerializeStruct::end(__serde_state)\n }\n }\n StructVariant::Untagged => {\n quote_block! {\n let #let_mut __serde_state = _serde::Serializer::serialize_struct(\n __serializer,\n #name,\n #len,\n )?;\n #(#serialize_fields)*\n _serde::ser::SerializeStruct::end(__serde_state)\n }\n }\n }\n}\n\nfn serialize_struct_variant_with_flatten(\n context: StructVariant,\n params: &Parameters,\n fields: &[Field],\n name: &Name,\n) -> Fragment {\n let struct_trait = StructTrait::SerializeMap;\n let serialize_fields = serialize_struct_visitor(fields, params, true, &struct_trait);\n\n let mut serialized_fields = fields\n .iter()\n .filter(|&field| !field.attrs.skip_serializing())\n .peekable();\n\n let let_mut = mut_if(serialized_fields.peek().is_some());\n\n match context {\n StructVariant::ExternallyTagged {\n variant_index,\n variant_name,\n } => {\n let this_type = ¶ms.this_type;\n let fields_ty = fields.iter().map(|f| &f.ty);\n let members = &fields.iter().map(|f| &f.member).collect::>();\n\n let (_, ty_generics, where_clause) = params.generics.split_for_impl();\n let wrapper_generics = bound::with_lifetime_bound(¶ms.generics, \"'__a\");\n let (wrapper_impl_generics, wrapper_ty_generics, _) = wrapper_generics.split_for_impl();\n\n quote_block! {\n #[doc(hidden)]\n struct __EnumFlatten #wrapper_generics #where_clause {\n data: (#(&'__a #fields_ty,)*),\n phantom: _serde::#private::PhantomData<#this_type #ty_generics>,\n }\n\n #[automatically_derived]\n impl #wrapper_impl_generics _serde::Serialize for __EnumFlatten #wrapper_ty_generics #where_clause {\n fn serialize<__S>(&self, __serializer: __S) -> _serde::#private::Result<__S::Ok, __S::Error>\n where\n __S: _serde::Serializer,\n {\n let (#(#members,)*) = self.data;\n let #let_mut __serde_state = _serde::Serializer::serialize_map(\n __serializer,\n _serde::#private::None)?;\n #(#serialize_fields)*\n _serde::ser::SerializeMap::end(__serde_state)\n }\n }\n\n _serde::Serializer::serialize_newtype_variant(\n __serializer,\n #name,\n #variant_index,\n #variant_name,\n &__EnumFlatten {\n data: (#(#members,)*),\n phantom: _serde::#private::PhantomData::<#this_type #ty_generics>,\n })\n }\n }\n StructVariant::InternallyTagged { tag, variant_name } => {\n quote_block! {\n let #let_mut __serde_state = _serde::Serializer::serialize_map(\n __serializer,\n _serde::#private::None)?;\n _serde::ser::SerializeMap::serialize_entry(\n &mut __serde_state,\n #tag,\n #variant_name,\n )?;\n #(#serialize_fields)*\n _serde::ser::SerializeMap::end(__serde_state)\n }\n }\n StructVariant::Untagged => {\n quote_block! {\n let #let_mut __serde_state = _serde::Serializer::serialize_map(\n __serializer,\n _serde::#private::None)?;\n #(#serialize_fields)*\n _serde::ser::SerializeMap::end(__serde_state)\n }\n }\n }\n}\n\nfn serialize_tuple_struct_visitor(\n fields: &[Field],\n params: &Parameters,\n is_enum: bool,\n tuple_trait: &TupleTrait,\n) -> Vec {\n let mut dst_fields = Vec::new();\n\n for (i, field) in fields.iter().enumerate() {\n if field.attrs.skip_serializing() {\n continue;\n }\n let mut field_expr = if is_enum {\n let id = field_i(i);\n quote!(#id)\n } else {\n get_member(\n params,\n field,\n &Member::Unnamed(Index {\n index: i as u32,\n span: Span::call_site(),\n }),\n )\n };\n\n let skip = field\n .attrs\n .skip_serializing_if()\n .map(|path| quote!(#path(#field_expr)));\n\n if let Some(path) = field.attrs.serialize_with() {\n field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr);\n }\n\n let span = field.original.span();\n let func = tuple_trait.serialize_element(span);\n let ser = quote! {\n #func(&mut __serde_state, #field_expr)?;\n };\n\n dst_fields.push(match skip {\n None => ser,\n Some(skip) => quote!(if !#skip { #ser }),\n });\n }\n dst_fields\n}\n\nfn serialize_struct_visitor(\n fields: &[Field],\n params: &Parameters,\n is_enum: bool,\n struct_trait: &StructTrait,\n) -> Vec {\n let mut dst_fields = Vec::new();\n\n for field in fields {\n if field.attrs.skip_serializing() {\n continue;\n }\n let member = &field.member;\n\n let mut field_expr = if is_enum {\n quote!(#member)\n } else {\n get_member(params, field, member)\n };\n\n let key_expr = field.attrs.name().serialize_name();\n\n let skip = field\n .attrs\n .skip_serializing_if()\n .map(|path| quote!(#path(#field_expr)));\n\n if let Some(path) = field.attrs.serialize_with() {\n field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr);\n }\n\n let span = field.original.span();\n let ser = if field.attrs.flatten() {\n let func = quote_spanned!(span=> _serde::Serialize::serialize);\n quote! {\n #func(&#field_expr, _serde::#private::ser::FlatMapSerializer(&mut __serde_state))?;\n }\n } else {\n let func = struct_trait.serialize_field(span);\n quote! {\n #func(&mut __serde_state, #key_expr, #field_expr)?;\n }\n };\n\n dst_fields.push(match skip {\n None => ser,\n Some(skip) => {\n if let Some(skip_func) = struct_trait.skip_field(span) {\n quote! {\n if !#skip {\n #ser\n } else {\n #skip_func(&mut __serde_state, #key_expr)?;\n }\n }\n } else {\n quote! {\n if !#skip {\n #ser\n }\n }\n }\n }\n });\n }\n dst_fields\n}\n\nfn wrap_serialize_field_with(\n params: &Parameters,\n field_ty: &syn::Type,\n serialize_with: &syn::ExprPath,\n field_expr: &TokenStream,\n) -> TokenStream {\n wrap_serialize_with(params, serialize_with, &[field_ty], &[quote!(#field_expr)])\n}\n\nfn wrap_serialize_variant_with(\n params: &Parameters,\n serialize_with: &syn::ExprPath,\n variant: &Variant,\n) -> TokenStream {\n let field_tys: Vec<_> = variant.fields.iter().map(|field| field.ty).collect();\n let field_exprs: Vec<_> = variant\n .fields\n .iter()\n .map(|field| {\n let id = match &field.member {\n Member::Named(ident) => ident.clone(),\n Member::Unnamed(member) => field_i(member.index as usize),\n };\n quote!(#id)\n })\n .collect();\n wrap_serialize_with(\n params,\n serialize_with,\n field_tys.as_slice(),\n field_exprs.as_slice(),\n )\n}\n\nfn wrap_serialize_with(\n params: &Parameters,\n serialize_with: &syn::ExprPath,\n field_tys: &[&syn::Type],\n field_exprs: &[TokenStream],\n) -> TokenStream {\n let this_type = ¶ms.this_type;\n let (_, ty_generics, where_clause) = params.generics.split_for_impl();\n\n let wrapper_generics = if field_exprs.is_empty() {\n params.generics.clone()\n } else {\n bound::with_lifetime_bound(¶ms.generics, \"'__a\")\n };\n let (wrapper_impl_generics, wrapper_ty_generics, _) = wrapper_generics.split_for_impl();\n\n let field_access = (0..field_exprs.len()).map(|n| {\n Member::Unnamed(Index {\n index: n as u32,\n span: Span::call_site(),\n })\n });\n\n let self_var = quote!(self);\n let serializer_var = quote!(__s);\n\n // If #serialize_with returns wrong type, error will be reported on here.\n // We attach span of the path to this piece so error will be reported\n // on the #[serde(with = \"...\")]\n // ^^^^^\n let wrapper_serialize = quote_spanned! {serialize_with.span()=>\n #serialize_with(#(#self_var.values.#field_access, )* #serializer_var)\n };\n\n quote!(&{\n #[doc(hidden)]\n struct __SerializeWith #wrapper_impl_generics #where_clause {\n values: (#(&'__a #field_tys, )*),\n phantom: _serde::#private::PhantomData<#this_type #ty_generics>,\n }\n\n #[automatically_derived]\n impl #wrapper_impl_generics _serde::Serialize for __SerializeWith #wrapper_ty_generics #where_clause {\n fn serialize<__S>(&#self_var, #serializer_var: __S) -> _serde::#private::Result<__S::Ok, __S::Error>\n where\n __S: _serde::Serializer,\n {\n #wrapper_serialize\n }\n }\n\n __SerializeWith {\n values: (#(#field_exprs, )*),\n phantom: _serde::#private::PhantomData::<#this_type #ty_generics>,\n }\n })\n}\n\n// Serialization of an empty struct results in code like:\n//\n// let mut __serde_state = serializer.serialize_struct(\"S\", 0)?;\n// _serde::ser::SerializeStruct::end(__serde_state)\n//\n// where we want to omit the `mut` to avoid a warning.\nfn mut_if(is_mut: bool) -> Option {\n if is_mut {\n Some(quote!(mut))\n } else {\n None\n }\n}\n\nfn get_member(params: &Parameters, field: &Field, member: &Member) -> TokenStream {\n let self_var = ¶ms.self_var;\n match (params.is_remote, field.attrs.getter()) {\n (false, None) => {\n if params.is_packed {\n quote!(&{#self_var.#member})\n } else {\n quote!(&#self_var.#member)\n }\n }\n (true, None) => {\n let inner = if params.is_packed {\n quote!(&{#self_var.#member})\n } else {\n quote!(&#self_var.#member)\n };\n let ty = field.ty;\n quote!(_serde::#private::ser::constrain::<#ty>(#inner))\n }\n (true, Some(getter)) => {\n let ty = field.ty;\n quote!(_serde::#private::ser::constrain::<#ty>(&#getter(#self_var)))\n }\n (false, Some(_)) => {\n unreachable!(\"getter is only allowed for remote impls\");\n }\n }\n}\n\nfn effective_style(variant: &Variant) -> Style {\n match variant.style {\n Style::Newtype if variant.fields[0].attrs.skip_serializing() => Style::Unit,\n other => other,\n }\n}\n\nenum StructTrait {\n SerializeMap,\n SerializeStruct,\n SerializeStructVariant,\n}\n\nimpl StructTrait {\n fn serialize_field(&self, span: Span) -> TokenStream {\n match *self {\n StructTrait::SerializeMap => {\n quote_spanned!(span=> _serde::ser::SerializeMap::serialize_entry)\n }\n StructTrait::SerializeStruct => {\n quote_spanned!(span=> _serde::ser::SerializeStruct::serialize_field)\n }\n StructTrait::SerializeStructVariant => {\n quote_spanned!(span=> _serde::ser::SerializeStructVariant::serialize_field)\n }\n }\n }\n\n fn skip_field(&self, span: Span) -> Option {\n match *self {\n StructTrait::SerializeMap => None,\n StructTrait::SerializeStruct => {\n Some(quote_spanned!(span=> _serde::ser::SerializeStruct::skip_field))\n }\n StructTrait::SerializeStructVariant => {\n Some(quote_spanned!(span=> _serde::ser::SerializeStructVariant::skip_field))\n }\n }\n }\n}\n\nenum TupleTrait {\n SerializeTuple,\n SerializeTupleStruct,\n SerializeTupleVariant,\n}\n\nimpl TupleTrait {\n fn serialize_element(&self, span: Span) -> TokenStream {\n match *self {\n TupleTrait::SerializeTuple => {\n quote_spanned!(span=> _serde::ser::SerializeTuple::serialize_element)\n }\n TupleTrait::SerializeTupleStruct => {\n quote_spanned!(span=> _serde::ser::SerializeTupleStruct::serialize_field)\n }\n TupleTrait::SerializeTupleVariant => {\n quote_spanned!(span=> _serde::ser::SerializeTupleVariant::serialize_field)\n }\n }\n }\n}", "messages": null, "tools": null} {"id": "8b4bd17fe457cf09", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/changes/index.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 1516, "sha256": "e43641675a4cb68d5fdae0b5d6b5f35fe5678e2124a78618c0b9e3eb531756e1", "text": "# Breaking Changes\n\nList of breaking changes in Vite including API deprecations, removals, and changes. Most of the changes below can be opt-in using the [`future` option](/config/shared-options.html#future) in your Vite config.\n\n## Planned\n\nThese changes are planned for the next major version of Vite. The deprecation or usage warnings will guide you where possible, and we're reaching out to framework, plugin authors, and users to apply these changes.\n\n- [`this.environment` in Hooks](/changes/this-environment-in-hooks)\n- [HMR `hotUpdate` Plugin Hook](/changes/hotupdate-hook)\n- [SSR Using `ModuleRunner` API](/changes/ssr-using-modulerunner)\n\n## Considering\n\nThese changes are being considered and are often experimental APIs that intend to improve upon current usage patterns. As not all changes are listed here, please check out the [Experimental Label in Vite GitHub Discussions](https://github.com/vitejs/vite/discussions/categories/feedback?discussions_q=label%3Aexperimental+category%3AFeedback) for the full list.\n\nWe don't recommend switching to these APIs yet. They are included in Vite to help us gather feedback. Please check these proposals and let us know how they work in your use case in each's linked GitHub Discussions.\n\n- [Move to Per-environment APIs](/changes/per-environment-apis)\n- [Shared Plugins During Build](/changes/shared-plugins-during-build)\n\n## Past\n\nThe changes below have been done or reverted. They are no longer relevant in the current major version.\n\n- _No past changes yet_", "messages": null, "tools": null} {"id": "8b6ab92ad1ecf90d", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/node/__tests__/shortcuts.spec.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 4907, "sha256": "993a48f468db5e2abf7249e828b3cb4847fffedf9fe364613f678bd03428e3f7", "text": "import type { Mock } from 'vitest'\nimport { describe, expect, test, vi } from 'vitest'\nimport { createServer } from '../server'\nimport { preview } from '../preview'\nimport { bindCLIShortcuts } from '../shortcuts'\n\ndescribe('bindCLIShortcuts', () => {\n test.each([\n ['dev server', () => createServer()],\n ['preview server', () => preview()],\n ])('binding custom shortcuts with the %s', async (_, startServer) => {\n const server = await startServer()\n\n try {\n const xAction = vi.fn()\n const yAction = vi.fn()\n\n bindCLIShortcuts(\n server,\n {\n customShortcuts: [\n { key: 'x', description: 'test x', action: xAction },\n { key: 'y', description: 'test y', action: yAction },\n ],\n },\n true,\n )\n\n expect.assert(\n server._shortcutsState?.rl,\n 'The readline interface should be defined after binding shortcuts.',\n )\n expect(xAction).not.toHaveBeenCalled()\n\n server._shortcutsState.rl.emit('line', 'x')\n await vi.waitFor(() => expect(xAction).toHaveBeenCalledOnce())\n\n const xUpdatedAction = vi.fn()\n const zAction = vi.fn()\n\n bindCLIShortcuts(\n server,\n {\n customShortcuts: [\n { key: 'x', description: 'test x updated', action: xUpdatedAction },\n { key: 'z', description: 'test z', action: zAction },\n ],\n },\n true,\n )\n\n expect(xUpdatedAction).not.toHaveBeenCalled()\n server._shortcutsState.rl.emit('line', 'x')\n await vi.waitFor(() => expect(xUpdatedAction).toHaveBeenCalledOnce())\n\n // Ensure original xAction is not called again\n expect(xAction).toHaveBeenCalledOnce()\n\n expect(yAction).not.toHaveBeenCalled()\n server._shortcutsState.rl.emit('line', 'y')\n await vi.waitFor(() => expect(yAction).toHaveBeenCalledOnce())\n\n expect(zAction).not.toHaveBeenCalled()\n server._shortcutsState.rl.emit('line', 'z')\n await vi.waitFor(() => expect(zAction).toHaveBeenCalledOnce())\n } finally {\n await server.close()\n }\n })\n\n test('rebinds shortcuts after server restart', async () => {\n const manualShortcutAction = vi.fn()\n const pluginShortcutActions: Array> = []\n\n const server = await createServer({\n plugins: [\n {\n name: 'custom-shortcut-plugin',\n configureServer(viteDevServer) {\n const action = vi.fn()\n\n // Keep track of actions created by the plugin\n // To verify if they are overwritten on server restart\n pluginShortcutActions.push(action)\n\n // Bind custom shortcut from plugin\n bindCLIShortcuts(\n viteDevServer,\n {\n customShortcuts: [\n {\n key: 'y',\n description: 'plugin shortcut',\n action,\n },\n ],\n },\n true,\n )\n },\n },\n ],\n })\n\n try {\n const readline = server._shortcutsState?.rl\n\n expect.assert(\n readline,\n 'The readline interface should be defined after binding shortcuts.',\n )\n\n readline.emit('line', 'y')\n await vi.waitFor(() => {\n expect(pluginShortcutActions).toHaveLength(1)\n expect(pluginShortcutActions[0]).toHaveBeenCalledOnce()\n })\n\n // Manually bind another custom shortcut\n bindCLIShortcuts(\n server,\n {\n customShortcuts: [\n {\n key: 'x',\n description: 'manual shortcut',\n action: manualShortcutAction,\n },\n ],\n },\n true,\n )\n\n readline.emit('line', 'x')\n await vi.waitFor(() =>\n expect(manualShortcutAction).toHaveBeenCalledOnce(),\n )\n\n // Check the order of shortcuts before restart\n expect(\n server._shortcutsState?.options.customShortcuts?.map((s) => s.key),\n ).toEqual(['x', 'y'])\n\n // Restart the server\n await server.restart()\n\n // Shortcut orders should be preserved after restart\n expect(\n server._shortcutsState?.options.customShortcuts?.map((s) => s.key),\n ).toEqual(['x', 'y'])\n\n expect.assert(\n server._shortcutsState?.rl === readline,\n 'The readline interface should be preserved.',\n )\n\n // Shortcuts should still work after restart\n readline.emit('line', 'x')\n await vi.waitFor(() =>\n expect(manualShortcutAction).toHaveBeenCalledTimes(2),\n )\n\n readline.emit('line', 'y')\n await vi.waitFor(() => {\n expect(pluginShortcutActions).toHaveLength(2)\n expect(pluginShortcutActions[1]).toHaveBeenCalledOnce()\n expect(pluginShortcutActions[0]).toHaveBeenCalledOnce()\n })\n } finally {\n await server.close()\n }\n })\n})", "messages": null, "tools": null} {"id": "8b9fcbddde4a41f9", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/features/parsing/json_lines.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 1799, "sha256": "d46211e0a637a73e3cff8b677f7d9201f40df0de4e3fbab65d0f60a7eb5695c4", "text": "# JSON Lines\n\nThe [JSON Lines](https://jsonlines.org) format is a text format of newline-delimited JSON. In particular:\n\n1. The input must be UTF-8 encoded.\n2. Every line must be a valid JSON value.\n3. The line separator must be `\\n`. As `\\r` is silently ignored, `\\r\\n` is also supported.\n4. The final character may be `\\n`, but is not required to be one.\n\n!!! example \"JSON Text example\"\n\n ```json\n {\"name\": \"Gilbert\", \"wins\": [[\"straight\", \"7♣\"], [\"one pair\", \"10♥\"]]}\n {\"name\": \"Alexa\", \"wins\": [[\"two pair\", \"4♠\"], [\"two pair\", \"9♠\"]]}\n {\"name\": \"May\", \"wins\": []}\n {\"name\": \"Deloise\", \"wins\": [[\"three of a kind\", \"5♣\"]]}\n ```\n\nJSON Lines input with more than one value is treated as invalid JSON by the [`parse`](../../api/basic_json/parse.md) or\n[`accept`](../../api/basic_json/accept.md) functions. To process it line by line, functions like\n[`std::getline`](https://en.cppreference.com/w/cpp/string/basic_string/getline) can be used:\n\n!!! example \"Example: Parse JSON Text input line by line\"\n\n The example below demonstrates how JSON Lines can be processed.\n\n ```cpp\n --8<-- \"examples/json_lines.cpp\"\n ```\n \n Output:\n\n ```json\n --8<-- \"examples/json_lines.output\"\n ```\n\n!!! warning \"Note\"\n\n Using [`operator>>`](../../api/operator_gtgt.md) like\n \n ```cpp\n json j;\n while (input >> j)\n {\n std::cout << j << std::endl;\n }\n ```\n \n with a JSON Lines input does not work, because the parser will try to parse one value after the last one.\n\n This is different from parsing a stream of *concatenated* (non-newline-delimited) JSON values, for which\n `operator>>` does work, provided that a value that is a number is followed by whitespace -- see its\n [notes](../../api/operator_gtgt.md#notes) for details.", "messages": null, "tools": null} {"id": "8bb1874a7f887e2f", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/src/unit-diagnostics.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 9700, "sha256": "ab4293089a16a096d1f2ed839c0b3b36ae9315ca15aec85355a29aae4b7d5b80", "text": "// __ _____ _____ _____\n// __| | __| | | | JSON for Modern C++ (supporting code)\n// | | |__ | | | | | | version 3.12.0\n// |_____|_____|_____|_|___| https://github.com/nlohmann/json\n//\n// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann \n// SPDX-License-Identifier: MIT\n\n#include \"doctest_compatibility.h\"\n\n#ifdef JSON_DIAGNOSTICS\n #undef JSON_DIAGNOSTICS\n#endif\n\n#define JSON_DIAGNOSTICS 1\n\n#include \nusing nlohmann::json;\n\nTEST_CASE(\"Better diagnostics\")\n{\n SECTION(\"empty JSON Pointer\")\n {\n json const j = 1;\n std::string s;\n CHECK_THROWS_WITH_AS(s = j.get(), \"[json.exception.type_error.302] type must be string, but is number\", json::type_error);\n }\n\n SECTION(\"invalid type\")\n {\n json j;\n j[\"a\"][\"b\"][\"c\"] = 1;\n std::string s;\n CHECK_THROWS_WITH_AS(s = j[\"a\"][\"b\"][\"c\"].get(), \"[json.exception.type_error.302] (/a/b/c) type must be string, but is number\", json::type_error);\n }\n\n SECTION(\"missing key\")\n {\n json j;\n j[\"object\"][\"object\"] = true;\n CHECK_THROWS_WITH_AS(j[\"object\"].at(\"not_found\"), \"[json.exception.out_of_range.403] (/object) key 'not_found' not found\", json::out_of_range);\n }\n\n SECTION(\"array index out of range\")\n {\n json j;\n j[\"array\"][4] = true;\n CHECK_THROWS_WITH_AS(j[\"array\"].at(5), \"[json.exception.out_of_range.401] (/array) array index 5 is out of range\", json::out_of_range);\n }\n\n SECTION(\"array index at wrong type\")\n {\n json j;\n j[\"array\"][4] = true;\n CHECK_THROWS_WITH_AS(j[\"array\"][4][5], \"[json.exception.type_error.305] (/array/4) cannot use operator[] with a numeric argument with boolean\", json::type_error);\n }\n\n SECTION(\"wrong iterator\")\n {\n json j;\n j[\"array\"] = json::array();\n CHECK_THROWS_WITH_AS(j[\"array\"].erase(j.begin()), \"[json.exception.invalid_iterator.202] (/array) iterator does not fit current value\", json::invalid_iterator);\n }\n\n SECTION(\"JSON Pointer escaping\")\n {\n json j;\n j[\"a/b\"][\"m~n\"] = 1;\n std::string s;\n CHECK_THROWS_WITH_AS(s = j[\"a/b\"][\"m~n\"].get(), \"[json.exception.type_error.302] (/a~1b/m~0n) type must be string, but is number\", json::type_error);\n }\n\n SECTION(\"Parse error\")\n {\n json _;\n CHECK_THROWS_WITH_AS(_ = json::parse(\"\"), \"[json.exception.parse_error.101] parse error at line 1, column 1: attempting to parse an empty input; check that your input string or stream contains the expected JSON\", json::parse_error);\n }\n\n SECTION(\"Wrong type in update()\")\n {\n json j = {{\"foo\", \"bar\"}};\n json k = {{\"bla\", 1}};\n\n CHECK_THROWS_WITH_AS(j.update(k[\"bla\"].begin(), k[\"bla\"].end()), \"[json.exception.type_error.312] (/bla) cannot use update() with number\", json::type_error);\n CHECK_THROWS_WITH_AS(j.update(k[\"bla\"]), \"[json.exception.type_error.312] (/bla) cannot use update() with number\", json::type_error);\n }\n}\n\nTEST_CASE(\"Regression tests for extended diagnostics\")\n{\n SECTION(\"Regression test for https://github.com/nlohmann/json/pull/2562#pullrequestreview-574858448\")\n {\n CHECK_THROWS_WITH_AS(json({\"0\", \"0\"})[1].get(), \"[json.exception.type_error.302] (/1) type must be number, but is string\", json::type_error);\n CHECK_THROWS_WITH_AS(json({\"0\", \"1\"})[1].get(), \"[json.exception.type_error.302] (/1) type must be number, but is string\", json::type_error);\n }\n\n SECTION(\"Regression test for https://github.com/nlohmann/json/pull/2562/files/380a613f2b5d32425021129cd1f371ddcfd54ddf#r563259793\")\n {\n json j;\n j[\"/foo\"] = {1, 2, 3};\n CHECK_THROWS_WITH_AS(j.unflatten(), \"[json.exception.type_error.315] (/~1foo) values in object must be primitive\", json::type_error);\n }\n\n SECTION(\"Regression test for issue #2838 - Assertion failure when inserting into arrays with JSON_DIAGNOSTICS set\")\n {\n // void push_back(basic_json&& val)\n {\n json j_arr = json::array();\n j_arr.push_back(json::object());\n j_arr.push_back(json::object());\n j_arr.push_back(json::object());\n j_arr.push_back(json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // void push_back(const basic_json& val)\n {\n json j_arr = json::array();\n auto object = json::object();\n j_arr.push_back(object);\n j_arr.push_back(object);\n j_arr.push_back(object);\n j_arr.push_back(object);\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // reference emplace_back(Args&& ... args)\n {\n json j_arr = json::array();\n j_arr.emplace_back(json::object());\n j_arr.emplace_back(json::object());\n j_arr.emplace_back(json::object());\n j_arr.emplace_back(json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // iterator insert(const_iterator pos, const basic_json& val)\n {\n json j_arr = json::array();\n j_arr.insert(j_arr.begin(), json::object());\n j_arr.insert(j_arr.begin(), json::object());\n j_arr.insert(j_arr.begin(), json::object());\n j_arr.insert(j_arr.begin(), json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // iterator insert(const_iterator pos, size_type cnt, const basic_json& val)\n {\n json j_arr = json::array();\n j_arr.insert(j_arr.begin(), 2, json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // iterator insert(const_iterator pos, const_iterator first, const_iterator last)\n {\n json j_arr = json::array();\n json j_objects = {json::object(), json::object()};\n j_arr.insert(j_arr.begin(), j_objects.begin(), j_objects.end());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n }\n\n SECTION(\"Regression test for issue #2962 - JSON_DIAGNOSTICS assertion for ordered_json\")\n {\n nlohmann::ordered_json j;\n nlohmann::ordered_json j2;\n const std::string value;\n j[\"first\"] = value;\n j[\"second\"] = value;\n j2[\"something\"] = j;\n }\n\n SECTION(\"Regression test for issue #3007 - Parent pointers properly set when using update()\")\n {\n // void update(const_reference j)\n {\n json j = json::object();\n\n {\n json j2 = json::object();\n j2[\"one\"] = 1;\n\n j.update(j2);\n }\n\n // Must call operator[] on const element, otherwise m_parent gets updated.\n auto const& constJ = j;\n CHECK_THROWS_WITH_AS(constJ[\"one\"].at(0), \"[json.exception.type_error.304] (/one) cannot use at() with number\", json::type_error);\n }\n\n // void update(const_iterator first, const_iterator last)\n {\n json j = json::object();\n\n {\n json j2 = json::object();\n j2[\"one\"] = 1;\n\n j.update(j2.begin(), j2.end());\n }\n\n // Must call operator[] on const element, otherwise m_parent gets updated.\n auto const& constJ = j;\n CHECK_THROWS_WITH_AS(constJ[\"one\"].at(0), \"[json.exception.type_error.304] (/one) cannot use at() with number\", json::type_error);\n }\n\n // Code from #3007 triggering unwanted assertion without fix to update().\n {\n json root = json::array();\n json lower = json::object();\n\n {\n json lowest = json::object();\n lowest[\"one\"] = 1;\n\n lower.update(lowest);\n }\n\n root.push_back(lower);\n }\n }\n\n SECTION(\"Regression test for issue #3032 - Yet another assertion failure when inserting into arrays with JSON_DIAGNOSTICS set\")\n {\n // reference operator[](size_type idx)\n {\n json j_arr = json::array();\n j_arr[0] = 0;\n j_arr[1] = 1;\n j_arr[2] = 2;\n j_arr[3] = 3;\n j_arr[4] = 4;\n j_arr[5] = 5;\n j_arr[6] = 6;\n j_arr[7] = 7;\n json const j_arr_copy = j_arr;\n }\n }\n\n SECTION(\"Regression test for issue #3915 - JSON_DIAGNOSTICS trigger assertion\")\n {\n json j = json::object();\n j[\"root\"] = \"root_str\";\n\n json jj = json::object();\n jj[\"child\"] = json::object();\n\n // If do not push anything in object, then no assert will be produced\n jj[\"child\"][\"prop1\"] = \"prop1_value\";\n\n // Push all properties of child in parent\n j.insert(jj.at(\"child\").begin(), jj.at(\"child\").end());\n\n // Here assert is generated when construct new json\n const json k(j);\n\n CHECK(k.dump() == \"{\\\"prop1\\\":\\\"prop1_value\\\",\\\"root\\\":\\\"root_str\\\"}\");\n }\n\n SECTION(\"Regression test for issue #4813 - update() with merge_objects=true triggers JSON_ASSERT with JSON_DIAGNOSTICS\")\n {\n // https://github.com/nlohmann/json/issues/4813\n nlohmann::ordered_json j1 = {{\"numbers\", {{\"one\", 1}}}};\n nlohmann::ordered_json const j2 = {{\"numbers\", {{\"two\", 2}}}, {\"string\", \"t\"}};\n CHECK_NOTHROW(j1.update(j2, true));\n CHECK(j1[\"numbers\"][\"one\"] == 1);\n CHECK(j1[\"numbers\"][\"two\"] == 2);\n CHECK(j1[\"string\"] == \"t\");\n }\n}", "messages": null, "tools": null} {"id": "8bd241b48016f0f0", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/optimize-deps-no-discovery/index.html", "lang": "html", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 525, "sha256": "79a6ff3a15b038dac52f0741b73157bafce8f34db6de11bf48b26b6b94166937", "text": "

Optimize Deps

\n\n

Optimized Dep

\n
\n\n

Vue & Vuex

\n
\n\n\n\n", "messages": null, "tools": null} {"id": "8c03184d6be16658", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/api/operator_ltlt.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 3026, "sha256": "4d8e9f49c5e7a134c9cd1f6e8dcd1c56df77252329c5ea97c3986b32d9b267c9", "text": "# nlohmann::operator<<(basic_json), nlohmann::operator<<(json_pointer)\n\n```cpp\nstd::ostream& operator<<(std::ostream& o, const basic_json& j); // (1)\n\nstd::ostream& operator<<(std::ostream& o, const json_pointer& ptr); // (2)\n```\n\n1. Serialize the given JSON value `j` to the output stream `o`. The JSON value will be serialized using the\n [`dump`](basic_json/dump.md) member function.\n - The indentation of the output can be controlled with the member variable `width` of the output stream `o`. For\n instance, using the manipulator `std::setw(4)` on `o` sets the indentation level to `4` and the serialization\n result is the same as calling `dump(4)`.\n - The indentation character can be controlled with the member variable `fill` of the output stream `o`.\n For instance, the manipulator `std::setfill('\\\\t')` sets indentation to use a tab character rather than the\n default space character.\n2. Write a string representation of the given JSON pointer `ptr` to the output stream `o`. The string representation is\n obtained using the [`to_string`](json_pointer/to_string.md) member function.\n\n## Parameters\n\n`o` (in, out)\n: stream to write to\n\n`j` (in)\n: JSON value to serialize\n\n`ptr` (in)\n: JSON pointer to write\n\n## Return value\n\nthe stream `o`\n\n## Exceptions\n\n1. Throws [`type_error.316`](../home/exceptions.md#jsonexceptiontype_error316) if a string stored inside the JSON\n value is not UTF-8 encoded. Note that unlike the [`dump`](basic_json/dump.md) member functions, no `error_handler`\n can be set.\n2. None.\n\n## Complexity\n\nLinear.\n\n## Notes\n\n!!! warning \"Deprecation\"\n\n Function `#!cpp std::ostream& operator<<(std::ostream& o, const basic_json& j)` replaces function\n `#!cpp std::ostream& operator>>(const basic_json& j, std::ostream& o)` which has been deprecated in version 3.0.0.\n It will be removed in version 4.0.0. Please replace calls like `#!cpp j >> o;` with `#!cpp o << j;`.\n\n## Examples\n\n??? example \"Example: (1) serialize JSON value to stream\"\n\n The example below shows the serialization with different parameters to `width` to adjust the indentation level.\n \n ```cpp\n --8<-- \"examples/operator_ltlt__basic_json.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/operator_ltlt__basic_json.output\"\n ```\n\n??? example \"Example: (2) write JSON pointer to stream\"\n\n The example below shows how to write a JSON pointer to a stream.\n \n ```cpp\n --8<-- \"examples/operator_ltlt__json_pointer.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/operator_ltlt__json_pointer.output\"\n ```\n\n## See also\n\n- [dump](basic_json/dump.md) - serialize to a JSON-formatted string\n- [Serialization](../features/serialization.md) - the serialization article\n\n## Version history\n\n1. Added in version 1.0.0. Added support for indentation character and deprecated\n `#!cpp std::ostream& operator>>(const basic_json& j, std::ostream& o)` in version 3.0.0.\n2. Added in version 3.11.0.", "messages": null, "tools": null} {"id": "8c5197ff79a2bc8f", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/node/constants.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 5612, "sha256": "c3d150e836674fe207c3be1160f250ace7e16af0430cc7156d7e661189e021d3", "text": "import path, { resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { readFileSync } from 'node:fs'\nimport type { RollupPluginHooks } from './typeUtils'\n\nconst { version } = JSON.parse(\n readFileSync(new URL('../../package.json', import.meta.url)).toString(),\n)\n\nexport const ROLLUP_HOOKS: RollupPluginHooks[] = [\n 'options',\n 'buildStart',\n 'buildEnd',\n 'renderStart',\n 'renderError',\n 'renderChunk',\n 'writeBundle',\n 'generateBundle',\n 'banner',\n 'footer',\n 'augmentChunkHash',\n 'outputOptions',\n // 'renderDynamicImport',\n // 'resolveFileUrl',\n // 'resolveImportMeta',\n 'intro',\n 'outro',\n 'closeBundle',\n 'closeWatcher',\n 'load',\n 'moduleParsed',\n 'watchChange',\n 'resolveDynamicImport',\n 'resolveId',\n // 'shouldTransformCachedModule',\n 'transform',\n 'onLog',\n]\n\nexport const VERSION = version as string\n\nconst DEFAULT_MAIN_FIELDS = [\n 'browser',\n 'module',\n 'jsnext:main', // moment still uses this...\n 'jsnext',\n]\nexport const DEFAULT_CLIENT_MAIN_FIELDS: readonly string[] =\n Object.freeze(DEFAULT_MAIN_FIELDS)\nexport const DEFAULT_SERVER_MAIN_FIELDS: readonly string[] = Object.freeze(\n DEFAULT_MAIN_FIELDS.filter((f) => f !== 'browser'),\n)\n\n/**\n * A special condition that would be replaced with production or development\n * depending on NODE_ENV env variable\n */\nexport const DEV_PROD_CONDITION = `development|production` as const\n\nconst DEFAULT_CONDITIONS = ['module', 'browser', 'node', DEV_PROD_CONDITION]\nexport const DEFAULT_CLIENT_CONDITIONS: readonly string[] = Object.freeze(\n DEFAULT_CONDITIONS.filter((c) => c !== 'node'),\n)\nexport const DEFAULT_SERVER_CONDITIONS: readonly string[] = Object.freeze(\n DEFAULT_CONDITIONS.filter((c) => c !== 'browser'),\n)\n\nexport const DEFAULT_EXTERNAL_CONDITIONS: readonly string[] = Object.freeze([\n 'node',\n 'module-sync',\n])\n\nexport const DEFAULT_EXTENSIONS: string[] = [\n '.mjs',\n '.js',\n '.mts',\n '.ts',\n '.jsx',\n '.tsx',\n '.json',\n]\n\n/**\n * The browser versions that are included in the Baseline Widely Available on 2025-05-01.\n *\n * This value would be bumped on each major release of Vite.\n *\n * The value is generated by `pnpm generate-target` script.\n */\nexport const ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET: string[] = [\n 'chrome111',\n 'edge111',\n 'firefox114',\n 'safari16.4',\n 'ios16.4',\n]\n\nexport const DEFAULT_CONFIG_FILES: string[] = [\n 'vite.config.js',\n 'vite.config.mjs',\n 'vite.config.ts',\n 'vite.config.cjs',\n 'vite.config.mts',\n 'vite.config.cts',\n]\n\nexport const JS_TYPES_RE: RegExp = /\\.(?:j|t)sx?$|\\.mjs$/\n\nexport const CSS_LANGS_RE: RegExp =\n /\\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\\?)/\n\nexport const OPTIMIZABLE_ENTRY_RE: RegExp = /\\.[cm]?[jt]s$/\n\nexport const SPECIAL_QUERY_RE: RegExp = /[?&](?:worker|sharedworker|raw|url)\\b/\n\n/**\n * Prefix for resolved fs paths, since windows paths may not be valid as URLs.\n */\nexport const FS_PREFIX = `/@fs/`\n\nexport const CLIENT_PUBLIC_PATH = `/@vite/client`\nexport const ENV_PUBLIC_PATH = `/@vite/env`\nexport const VITE_PACKAGE_DIR: string = resolve(\n fileURLToPath(import.meta.url),\n '../../..',\n)\n\nexport const CLIENT_ENTRY: string = resolve(\n VITE_PACKAGE_DIR,\n 'dist/client/client.mjs',\n)\nexport const BUNDLED_DEV_CLIENT_ENTRY: string = resolve(\n VITE_PACKAGE_DIR,\n 'dist/client/bundledDevClient.mjs',\n)\n/** URL filename the bundled-dev server serves the vite client under */\nexport const BUNDLED_DEV_CLIENT_FILENAME: string = 'bundledDevClient.mjs'\nexport const ENV_ENTRY: string = resolve(\n VITE_PACKAGE_DIR,\n 'dist/client/env.mjs',\n)\nexport const CLIENT_DIR: string = path.dirname(CLIENT_ENTRY)\n\n// ** READ THIS ** before editing `KNOWN_ASSET_TYPES`.\n// If you add an asset to `KNOWN_ASSET_TYPES`, make sure to also add it\n// to the TypeScript declaration file `packages/vite/client.d.ts` and\n// add a mime type to the `registerCustomMime` in\n// `packages/vite/src/node/plugin/assets.ts` if mime type cannot be\n// looked up by mrmime.\n// You can check if the mime type can be looked up by mrmime by running\n// `node --print \"require('mrmime').lookup('foo.png')\"`\nexport const KNOWN_ASSET_TYPES: string[] = [\n // images\n 'apng',\n 'bmp',\n 'png',\n 'jpe?g',\n 'jfif',\n 'pjpeg',\n 'pjp',\n 'gif',\n 'svg',\n 'ico',\n 'webp',\n 'avif',\n 'cur',\n 'jxl',\n\n // media\n 'mp4',\n 'webm',\n 'ogg',\n 'mp3',\n 'wav',\n 'flac',\n 'aac',\n 'opus',\n 'mov',\n 'm4a',\n 'vtt',\n\n // fonts\n 'woff2?',\n 'eot',\n 'ttf',\n 'otf',\n\n // other\n 'webmanifest',\n 'pdf',\n 'txt',\n]\n\nexport const DEFAULT_ASSETS_RE: RegExp = new RegExp(\n `\\\\.(` + KNOWN_ASSET_TYPES.join('|') + `)(\\\\?.*)?$`,\n 'i',\n)\n\nexport const DEP_VERSION_RE: RegExp = /[?&](v=[\\w.-]+)\\b/\n\nexport const loopbackHosts: Set = new Set([\n 'localhost',\n '127.0.0.1',\n '::1',\n '0000:0000:0000:0000:0000:0000:0000:0001',\n])\nexport const wildcardHosts: Set = new Set([\n '0.0.0.0',\n '::',\n '0000:0000:0000:0000:0000:0000:0000:0000',\n])\n\nexport const DEFAULT_DEV_PORT = 5173\n\nexport const DEFAULT_PREVIEW_PORT = 4173\n\nexport const DEFAULT_ASSETS_INLINE_LIMIT = 4096\n\n// the regex to allow loopback address origins:\n// - localhost domains (which will always resolve to the loopback address by RFC 6761 section 6.3)\n// - 127.0.0.1\n// - ::1\nexport const defaultAllowedOrigins: RegExp =\n /^https?:\\/\\/(?:(?:[^:]+\\.)?localhost|127\\.0\\.0\\.1|\\[::1\\])(?::\\d+)?$/\n\nexport const METADATA_FILENAME = '_metadata.json'\n\nexport const ERR_OPTIMIZE_DEPS_PROCESSING_ERROR =\n 'ERR_OPTIMIZE_DEPS_PROCESSING_ERROR'\nexport const ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR =\n 'ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR'", "messages": null, "tools": null} {"id": "8c90060b7cb1097b", "category": "code", "domain": "code", "source": "fmt", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "include/fmt/xchar.h", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/fmtlib/fmt", "commit": "4f645a8d5d7aa6f8c5ba57e9af0396e4761d3f81", "collector": "tools/harvest.py"}, "chars": 14245, "sha256": "21b3c064df93fee6065004786202b2022f143bd789102e3ef6c8767ae5572cc0", "text": "// Formatting library for C++ - optional wchar_t and exotic character support\n//\n// Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors\n// All rights reserved.\n//\n// For the license information refer to format.h.\n\n#ifndef FMT_XCHAR_H_\n#define FMT_XCHAR_H_\n\n#include \"color.h\"\n#include \"format.h\"\n#include \"ostream.h\"\n#include \"ranges.h\"\n\n#ifndef FMT_MODULE\n# include \n# if FMT_USE_LOCALE\n# include \n# endif\n#endif\n\nFMT_BEGIN_NAMESPACE\nnamespace detail {\n\ntemplate \nusing is_exotic_char = bool_constant::value>;\n\ntemplate struct format_string_char {};\n\ntemplate \nstruct format_string_char<\n S, void_t())))>> {\n using type = char_t;\n};\n\ntemplate \nstruct format_string_char<\n S, enable_if_t::value>> {\n using type = typename S::char_type;\n};\n\ntemplate \nusing format_string_char_t = typename format_string_char::type;\n\ninline auto write_loc(basic_appender out, loc_value value,\n const format_specs& specs, locale_ref loc) -> bool {\n#if FMT_USE_LOCALE\n auto loc_copy = loc.get();\n auto& numpunct = std::use_facet>(loc_copy);\n auto separator = std::wstring();\n auto grouping = numpunct.grouping();\n if (!grouping.empty()) separator = std::wstring(1, numpunct.thousands_sep());\n return value.visit(loc_writer{out, specs, separator, grouping, {}});\n#endif\n return false;\n}\n\ntemplate \nvoid vformat_to(buffer& buf, basic_string_view fmt,\n basic_format_args> args,\n locale_ref loc = {}) {\n static_assert(!std::is_same::value, \"\");\n auto out = basic_appender(buf);\n parse_format_string(\n fmt, format_handler{parse_context(fmt), {out, args, loc}});\n}\n} // namespace detail\n\nFMT_BEGIN_EXPORT\n\nusing wstring_view = basic_string_view;\nusing wformat_parse_context = parse_context;\nusing wformat_context = buffered_context;\nusing wformat_args = basic_format_args;\nusing wmemory_buffer = basic_memory_buffer;\n\ntemplate struct basic_fstring {\n private:\n basic_string_view str_;\n\n static constexpr int num_static_named_args =\n detail::count_static_named_args();\n\n using checker = detail::format_string_checker<\n Char, static_cast(sizeof...(T)), num_static_named_args,\n num_static_named_args != detail::count_named_args()>;\n\n using arg_pack = detail::arg_pack;\n\n public:\n using t = basic_fstring;\n\n template >::value)>\n FMT_CONSTEVAL FMT_ALWAYS_INLINE basic_fstring(const S& s) : str_(s) {\n if (FMT_USE_CONSTEVAL)\n detail::parse_format_string(s, checker(s, arg_pack()));\n }\n template ::value&&\n std::is_same::value)>\n FMT_ALWAYS_INLINE basic_fstring(const S&) : str_(S()) {\n FMT_CONSTEXPR auto sv = basic_string_view(S());\n FMT_CONSTEXPR int ignore =\n (parse_format_string(sv, checker(sv, arg_pack())), 0);\n detail::ignore_unused(ignore);\n }\n basic_fstring(runtime_format_string fmt) : str_(fmt.str) {}\n\n FMT_DEPRECATED operator basic_string_view() const { return str_; }\n auto get() const -> basic_string_view { return str_; }\n};\n\ntemplate \nusing basic_format_string = basic_fstring;\n\ntemplate \nusing wformat_string = typename basic_format_string::t;\ninline auto runtime(wstring_view s) -> runtime_format_string {\n return {{s}};\n}\n\ntemplate \nconstexpr auto make_wformat_args(T&... args)\n -> decltype(fmt::make_format_args(args...)) {\n return fmt::make_format_args(args...);\n}\n\n#if !FMT_USE_NONTYPE_TEMPLATE_ARGS\ninline namespace literals {\ninline auto operator\"\"_a(const wchar_t* s, size_t) -> detail::udl_arg {\n return {s};\n}\n} // namespace literals\n#endif\n\ntemplate \nauto arg(const wchar_t* name, const T& arg) -> named_arg {\n return {name, arg};\n}\n\ntemplate ()))::value_type,\n FMT_ENABLE_IF(detail::is_exotic_char::value)>\nauto join(It begin, Sentinel end, S&& sep) -> join_view {\n return {begin, end, detail::to_string_view(sep)};\n}\n\ntemplate ()))::value_type,\n FMT_ENABLE_IF(detail::is_exotic_char::value &&\n !is_tuple_like::value)>\nauto join(Range&& range, S&& sep)\n -> join_view {\n return {std::begin(range), std::end(range), detail::to_string_view(sep)};\n}\n\ntemplate \nFMT_DEPRECATED auto join(std::initializer_list list, wstring_view sep)\n -> join_view {\n return join(std::begin(list), std::end(list), sep);\n}\n\ntemplate ()))::value_type,\n FMT_ENABLE_IF(detail::is_exotic_char::value&&\n is_tuple_like::value)>\nauto join(const Tuple& tuple, S&& sep) -> tuple_join_view {\n return {tuple, detail::to_string_view(sep)};\n}\n\ntemplate ::value)>\nauto vformat(basic_string_view fmt,\n basic_format_args> args)\n -> std::basic_string {\n auto buf = basic_memory_buffer();\n detail::vformat_to(buf, fmt, args);\n return {buf.data(), buf.size()};\n}\n\ntemplate \nauto format(wformat_string fmt, T&&... args) -> std::wstring {\n return vformat(fmt.get(), fmt::make_wformat_args(args...));\n}\n\ntemplate \nauto format_to(OutputIt out, wformat_string fmt, T&&... args)\n -> OutputIt {\n return vformat_to(out, fmt.get(), fmt::make_wformat_args(args...));\n}\n\n// Pass char_t as a default template parameter instead of using\n// std::basic_string> to reduce the symbol size.\ntemplate ,\n FMT_ENABLE_IF(!std::is_same::value &&\n !std::is_same::value)>\nauto format(const S& fmt, T&&... args) -> std::basic_string {\n return vformat(detail::to_string_view(fmt),\n fmt::make_format_args>(args...));\n}\n\ntemplate ,\n FMT_ENABLE_IF(detail::is_exotic_char::value)>\ninline auto vformat(locale_ref loc, const S& fmt,\n basic_format_args> args)\n -> std::basic_string {\n auto buf = basic_memory_buffer();\n detail::vformat_to(buf, detail::to_string_view(fmt), args, loc);\n return {buf.data(), buf.size()};\n}\n\ntemplate ,\n FMT_ENABLE_IF(detail::is_exotic_char::value)>\ninline auto format(locale_ref loc, const S& fmt, T&&... args)\n -> std::basic_string {\n return vformat(loc, detail::to_string_view(fmt),\n fmt::make_format_args>(args...));\n}\n\ntemplate ,\n FMT_ENABLE_IF(detail::is_output_iterator::value&&\n detail::is_exotic_char::value)>\nauto vformat_to(OutputIt out, const S& fmt,\n basic_format_args> args) -> OutputIt {\n auto&& buf = detail::get_buffer(out);\n detail::vformat_to(buf, detail::to_string_view(fmt), args);\n return detail::get_iterator(buf, out);\n}\n\ntemplate ,\n FMT_ENABLE_IF(detail::is_output_iterator::value &&\n !std::is_same::value &&\n !std::is_same::value)>\ninline auto format_to(OutputIt out, const S& fmt, T&&... args) -> OutputIt {\n return vformat_to(out, detail::to_string_view(fmt),\n fmt::make_format_args>(args...));\n}\n\ntemplate ,\n FMT_ENABLE_IF(detail::is_output_iterator::value&&\n detail::is_exotic_char::value)>\ninline auto vformat_to(OutputIt out, locale_ref loc, const S& fmt,\n basic_format_args> args)\n -> OutputIt {\n auto&& buf = detail::get_buffer(out);\n vformat_to(buf, detail::to_string_view(fmt), args, loc);\n return detail::get_iterator(buf, out);\n}\n\ntemplate ,\n bool enable = detail::is_output_iterator::value &&\n detail::is_exotic_char::value>\ninline auto format_to(OutputIt out, locale_ref loc, const S& fmt, T&&... args)\n -> typename std::enable_if::type {\n return vformat_to(out, loc, detail::to_string_view(fmt),\n fmt::make_format_args>(args...));\n}\n\ntemplate ::value&&\n detail::is_exotic_char::value)>\ninline auto vformat_to_n(OutputIt out, size_t n, basic_string_view fmt,\n basic_format_args> args)\n -> format_to_n_result {\n using traits = detail::fixed_buffer_traits;\n auto buf = detail::iterator_buffer(out, n);\n detail::vformat_to(buf, fmt, args);\n return {buf.out(), buf.count()};\n}\n\ntemplate ::value)>\nFMT_INLINE auto format_to_n(OutputIt out, size_t n, wformat_string fmt,\n T&&... args) -> format_to_n_result {\n return vformat_to_n(out, n, fmt.get(), fmt::make_wformat_args(args...));\n}\n\ntemplate ,\n FMT_ENABLE_IF(detail::is_output_iterator::value &&\n !std::is_same::value &&\n !std::is_same::value)>\ninline auto format_to_n(OutputIt out, size_t n, const S& fmt, T&&... args)\n -> format_to_n_result {\n return vformat_to_n(out, n, fmt::basic_string_view(fmt),\n fmt::make_format_args>(args...));\n}\n\ntemplate ,\n FMT_ENABLE_IF(detail::is_exotic_char::value)>\ninline auto formatted_size(const S& fmt, T&&... args) -> size_t {\n auto buf = detail::counting_buffer();\n detail::vformat_to(buf, detail::to_string_view(fmt),\n fmt::make_format_args>(args...));\n return buf.count();\n}\n\ninline void vprint(std::FILE* f, wstring_view fmt, wformat_args args) {\n auto buf = wmemory_buffer();\n detail::vformat_to(buf, fmt, args);\n buf.push_back(L'\\0');\n if (std::fputws(buf.data(), f) == -1)\n FMT_THROW(system_error(errno, FMT_STRING(\"cannot write to file\")));\n}\n\ninline void vprint(wstring_view fmt, wformat_args args) {\n vprint(stdout, fmt, args);\n}\n\ntemplate \nvoid print(std::FILE* f, wformat_string fmt, T&&... args) {\n return vprint(f, fmt.get(), fmt::make_wformat_args(args...));\n}\n\ntemplate void print(wformat_string fmt, T&&... args) {\n return vprint(fmt.get(), fmt::make_wformat_args(args...));\n}\n\ntemplate \nvoid println(std::FILE* f, wformat_string fmt, T&&... args) {\n return print(f, L\"{}\\n\", fmt::format(fmt, std::forward(args)...));\n}\n\ntemplate void println(wformat_string fmt, T&&... args) {\n return print(L\"{}\\n\", fmt::format(fmt, std::forward(args)...));\n}\n\ninline auto vformat(text_style ts, wstring_view fmt, wformat_args args)\n -> std::wstring {\n auto buf = wmemory_buffer();\n detail::vformat_to(buf, ts, fmt, args);\n return {buf.data(), buf.size()};\n}\n\ntemplate \ninline auto format(text_style ts, wformat_string fmt, T&&... args)\n -> std::wstring {\n return fmt::vformat(ts, fmt.get(), fmt::make_wformat_args(args...));\n}\n\ninline void vprint(std::wostream& os, wstring_view fmt, wformat_args args) {\n auto buffer = basic_memory_buffer();\n detail::vformat_to(buffer, fmt, args);\n detail::write_buffer(os, buffer);\n}\n\ntemplate \nvoid print(std::wostream& os, wformat_string fmt, T&&... args) {\n vprint(os, fmt.get(),\n fmt::make_format_args>(args...));\n}\n\ntemplate \nvoid println(std::wostream& os, wformat_string fmt, T&&... args) {\n print(os, L\"{}\\n\", fmt::format(fmt, std::forward(args)...));\n}\n\n/// Converts `value` to `std::wstring` using the default format for type `T`.\ntemplate inline auto to_wstring(const T& value) -> std::wstring {\n return format(FMT_STRING(L\"{}\"), value);\n}\nFMT_END_EXPORT\nFMT_END_NAMESPACE\n\n#endif // FMT_XCHAR_H_", "messages": null, "tools": null} {"id": "8d6640cf3b0747f7", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/tsconfig-json-load-error/__tests__/tsconfig-json-load-error.spec.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 2745, "sha256": "1bee0460fca48963e2a1344c04450770a07af961530a899d11a81d664c59260c", "text": "import { describe, expect, test } from 'vitest'\nimport { clearServeError, serveError } from './serve'\nimport {\n browserLogs,\n editFile,\n isBuild,\n isBundledDev,\n isServe,\n page,\n readFile,\n} from '~utils'\n\nconst tsconfigLoadErrorRE =\n /(\\[TSCONFIG_ERROR\\] )*Failed to load tsconfig|JSONError/\n\ndescribe.runIf(isBuild)('build', () => {\n test('should throw an error on build', () => {\n expect(serveError).toBeTruthy()\n expect(serveError.message).toMatch(tsconfigLoadErrorRE)\n clearServeError() // got expected error, null it here so testsuite does not fail from rethrow in afterAll\n })\n\n test('should not output files to dist', () => {\n let err\n try {\n readFile('dist/index.html')\n } catch (e) {\n err = e\n }\n expect(err).toBeTruthy()\n expect(err.code).toBe('ENOENT')\n })\n})\n\ndescribe.runIf(isServe)('server', () => {\n test.runIf(!isBundledDev)(\n 'should log 500 error in browser for malformed tsconfig',\n () => {\n // don't test for actual complete message as this might be locale dependent. chrome does log 500 consistently though\n expect(browserLogs.find((x) => x.includes('500'))).toBeTruthy()\n expect(browserLogs).not.toContain('tsconfig error fixed, file loaded')\n },\n )\n\n test.runIf(isBundledDev)(\n 'should keep the fallback page for malformed tsconfig',\n async () => {\n // bundled dev does not request modules one by one, so nothing can\n // answer with 500. The first build failed, so the server keeps serving\n // the fallback page with status 200. The error shows up in the overlay\n // instead, which the next test checks.\n expect(\n await page.evaluate(\n () => (globalThis as any).__vite_is_fallback_page__,\n ),\n ).toBe(true)\n expect(browserLogs).not.toContain('tsconfig error fixed, file loaded')\n },\n )\n\n test('should show error overlay for tsconfig error', async () => {\n const errorOverlay = await page.waitForSelector('vite-error-overlay')\n expect(errorOverlay).toBeTruthy()\n const message = await errorOverlay.$$eval('.message-body', (m) => {\n return m[0].innerHTML\n })\n // use regex with variable filename and position values because they are different on win\n expect(message).toMatch(tsconfigLoadErrorRE)\n })\n\n // bundled dev: no rebuild after initial-build failure yet (vitejs/vite#23028, rolldown#9598)\n test.skipIf(isBundledDev)(\n 'should reload when tsconfig is changed',\n async () => {\n editFile('has-error/tsconfig.json', (content) => {\n return content.replace('\"compilerOptions\":', '\"compilerOptions\":{}')\n })\n await expect\n .poll(() => browserLogs)\n .toContain('tsconfig error fixed, file loaded')\n },\n )\n})", "messages": null, "tools": null} {"id": "8d737651ce7168ad", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/thirdparty/Fuzzer/test/StrstrTest.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 753, "sha256": "9df674de665df8b4d0adf117b3b288e9bdd3e4268e63e2befe5677a897937f57", "text": "// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n\n// Test strstr and strcasestr hooks.\n#include \n#include \n#include \n#include \n#include \n\n// Windows does not have strcasestr and memmem, so we are not testing them.\n#ifdef _WIN32\n#define strcasestr strstr\n#define memmem(a, b, c, d) true\n#endif\n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {\n if (Size < 4) return 0;\n std::string s(reinterpret_cast(Data), Size);\n if (strstr(s.c_str(), \"FUZZ\") &&\n strcasestr(s.c_str(), \"aBcD\") &&\n memmem(s.data(), s.size(), \"kuku\", 4)\n ) {\n fprintf(stderr, \"BINGO\\n\");\n exit(1);\n }\n return 0;\n}", "messages": null, "tools": null} {"id": "8dadb4789cc6ce04", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/api/basic_json/is_structured.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 1392, "sha256": "682917667b37bf28e8aedb7ffac79221ed5120663fd383391497e166b899480c", "text": "# nlohmann::basic_json::is_structured\n\n```cpp\nconstexpr bool is_structured() const noexcept;\n```\n\nThis function returns `#!cpp true` if and only if the JSON type is structured (array or object).\n \n## Return value\n\n`#!cpp true` if type is structured (array or object), `#!cpp false` otherwise.\n\n## Exception safety\n\nNo-throw guarantee: this member function never throws exceptions.\n\n## Complexity\n\nConstant.\n\n## Possible implementation\n\n```cpp\nconstexpr bool is_structured() const noexcept\n{\n return is_array() || is_object();\n}\n```\n\n## Notes\n\nThe term *structured* stems from [RFC 8259](https://tools.ietf.org/html/rfc8259):\n\n> JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and\n> arrays).\n\nNote that though strings are containers in C++, they are treated as primitive values in JSON.\n\n## Examples\n\n??? example\n\n The following code exemplifies `is_structured()` for all JSON types.\n \n ```cpp\n --8<-- \"examples/is_structured.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/is_structured.output\"\n ```\n\n## See also\n\n- [is_primitive()](is_primitive.md) returns whether JSON value is primitive\n- [is_array()](is_array.md) returns whether the value is an array\n- [is_object()](is_object.md) returns whether the value is an object\n\n## Version history\n\n- Added in version 1.0.0.", "messages": null, "tools": null} {"id": "8e41e657bda3dac2", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/get_binary.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 407, "sha256": "d30ddf7dc5ce31812934e55629403fec8a95ced43e8bb626ccace95861b5ac33", "text": "#include \n#include \n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a binary vector\n std::vector vec = {0xCA, 0xFE, 0xBA, 0xBE};\n\n // create a binary JSON value with subtype 42\n json j = json::binary(vec, 42);\n\n // output type and subtype\n std::cout << \"type: \" << j.type_name() << \", subtype: \" << j.get_binary().subtype() << std::endl;\n}", "messages": null, "tools": null} {"id": "8f1fca29797cc48e", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/hmr/intermediate-file-delete/index.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 442, "sha256": "0ef867722f69d897ccbb1cdcec6a2b513c1d6b3a130fd5fb13e31efaeab7c928", "text": "import { displayCount } from './re-export.js'\n\nconst button = document.querySelector('.intermediate-file-delete-increment')\n\nconst render = () => {\n document.querySelector('.intermediate-file-delete-display').textContent =\n displayCount(Number(button.textContent))\n}\n\nrender()\n\nbutton.addEventListener('click', () => {\n button.textContent = `${Number(button.textContent) + 1}`\n render()\n})\n\nif (import.meta.hot) import.meta.hot.accept()", "messages": null, "tools": null} {"id": "8fedf43c3fe5a3d1", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/optimize-deps/dep-with-builtin-module-cjs/index.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 583, "sha256": "bfa3120a71d24f05074df3cb2732946768404a055d2bee50697cbc0d6476d918", "text": "// no node: protocol intentionally\n// eslint-disable-next-line n/prefer-node-protocol\nconst fs = require('fs')\n// eslint-disable-next-line n/prefer-node-protocol\nconst path = require('path')\n\n// NOTE: require destructure would error immediately because of how esbuild\n// compiles it. There's no way around it as it's direct property access, which\n// triggers the Proxy get trap.\n\n// access from default import\ntry {\n path.join()\n} catch (e) {\n console.log('dep-with-builtin-module-cjs', e)\n}\n\n// access from function\nmodule.exports.read = () => {\n return fs.readFileSync('test')\n}", "messages": null, "tools": null} {"id": "903fba7597d0f363", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/node/__tests__/runnerImport.spec.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 2694, "sha256": "89e26ac687467eab679df2c98f52b86163aee4b182e71d957b135bc8ea142869", "text": "import { resolve } from 'node:path'\nimport { describe, expect, test } from 'vitest'\nimport { loadConfigFromFile } from 'vite'\nimport { runnerImport } from '../ssr/runnerImport'\nimport { slash } from '../../shared/utils'\n\n// eslint-disable-next-line n/no-unsupported-features/node-builtins\nconst isTypeStrippingSupported = !!process.features.typescript\n\ndescribe('importing files using inlined environment', () => {\n const fixture = (name: string) =>\n resolve(import.meta.dirname, './fixtures/runner-import', name)\n\n test('importing a basic file works', async () => {\n const { module } = await runnerImport<\n typeof import('./fixtures/runner-import/basic')\n >(fixture('basic'))\n expect(module.test).toEqual({\n field: true,\n })\n })\n\n test(\"cannot import cjs, 'runnerImport' doesn't support CJS syntax at all\", async () => {\n await expect(() =>\n runnerImport(\n fixture('cjs.js'),\n ),\n ).rejects.toThrow('module is not defined')\n })\n\n test('can import vite config', async () => {\n const { module, dependencies } = await runnerImport<\n typeof import('./fixtures/runner-import/vite.config')\n >(fixture('vite.config'))\n expect(module.default).toEqual({\n root: './test',\n plugins: [\n {\n name: 'test',\n },\n ],\n })\n expect(dependencies).toEqual([slash(fixture('plugin.ts'))])\n })\n\n test('can import vite config that imports a TS external module', async () => {\n const { module, dependencies } = await runnerImport<\n typeof import('./fixtures/runner-import/vite.config.outside-pkg-import.mjs')\n >(fixture('vite.config.outside-pkg-import.mts'))\n\n expect(module.default.__injected).toBe(true)\n expect(dependencies).toEqual([\n slash(resolve(import.meta.dirname, './packages/parent/index.ts')),\n ])\n\n // confirm that it fails with a bundle approach\n if (!isTypeStrippingSupported) {\n await expect(async () => {\n const root = resolve(import.meta.dirname, './fixtures/runner-import')\n await loadConfigFromFile(\n { mode: 'production', command: 'serve' },\n resolve(root, './vite.config.outside-pkg-import.mts'),\n root,\n 'silent',\n )\n }).rejects.toThrow('Unknown file extension \".ts\"')\n }\n })\n\n test('dynamic import', async () => {\n const { module } = await runnerImport(fixture('dynamic-import.ts'))\n await expect(() => module.default()).rejects.toMatchInlineSnapshot(\n `[Error: Vite module runner has been closed.]`,\n )\n // const dep = await module.default();\n // expect(dep.default).toMatchInlineSnapshot(`\"ok\"`)\n })\n})", "messages": null, "tools": null} {"id": "90609b170a800ea6", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/node/ssr/ssrStacktrace.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 3441, "sha256": "11ee515263149b187085ed124003b2af9ba6df13ae0c7f7b09239cbcc0030321", "text": "import path from 'node:path'\nimport { TraceMap, originalPositionFor } from '@jridgewell/trace-mapping'\nimport type { EnvironmentModuleGraph } from '..'\n\nlet offset: number\n\nfunction calculateOffsetOnce() {\n if (offset !== undefined) {\n return\n }\n\n try {\n // `\"use strict\";` mirrors the directive prepended on its own line by\n // `ESModulesEvaluator`\n new Function('\"use strict\";\\nthrow new Error(1)')()\n } catch (e) {\n // in Node 12, stack traces account for the function wrapper.\n // in Node 13 and later, the function wrapper adds two lines,\n // which must be subtracted to generate a valid mapping\n const match = /:(\\d+):\\d+\\)$/.exec(e.stack.split('\\n')[1])\n offset = match ? +match[1] - 1 : 0\n }\n}\n\nexport function ssrRewriteStacktrace(\n stack: string,\n moduleGraph: EnvironmentModuleGraph,\n): { result: string; alreadyRewritten: boolean } {\n calculateOffsetOnce()\n\n let alreadyRewritten = false\n const rewritten = stack\n .split('\\n')\n .map((line) => {\n return line.replace(\n /^ {4}at (?:(\\S.*?)\\s\\()?(.+?):(\\d+)(?::(\\d+))?\\)?/,\n (input, varName, id, originalLine, originalColumn) => {\n if (!id) return input\n\n const mod = moduleGraph.getModuleById(id)\n const rawSourceMap = mod?.transformResult?.map\n\n if (!rawSourceMap) {\n return input\n }\n\n const traced = new TraceMap(rawSourceMap as any)\n const line = Number(originalLine) - offset\n // stacktrace's column is 1-indexed, but sourcemap's one is 0-indexed\n const column = Number(originalColumn) - 1\n if (line <= 0 || column < 0) {\n alreadyRewritten = true\n return input\n }\n\n const pos = originalPositionFor(traced, { line, column })\n if (!pos.source) {\n return input\n }\n\n const trimmedVarName = varName?.trim()\n const sourceFile = path.resolve(path.dirname(id), pos.source)\n // stacktrace's column is 1-indexed, but sourcemap's one is 0-indexed\n const source = `${sourceFile}:${pos.line}:${pos.column + 1}`\n if (!trimmedVarName || trimmedVarName === 'eval') {\n return ` at ${source}`\n } else {\n return ` at ${trimmedVarName} (${source})`\n }\n },\n )\n })\n .join('\\n')\n return { result: rewritten, alreadyRewritten }\n}\n\nexport function rebindErrorStacktrace(e: Error, stacktrace: string): void {\n const { configurable, writable } = Object.getOwnPropertyDescriptor(\n e,\n 'stack',\n )!\n if (configurable) {\n Object.defineProperty(e, 'stack', {\n value: stacktrace,\n enumerable: true,\n configurable: true,\n writable: true,\n })\n } else if (writable) {\n e.stack = stacktrace\n }\n}\n\nconst rewroteStacktraces = new WeakSet()\n\nexport function ssrFixStacktrace(\n e: Error,\n moduleGraph: EnvironmentModuleGraph,\n): void {\n if (!e.stack) return\n // stacktrace shouldn't be rewritten more than once\n if (rewroteStacktraces.has(e)) return\n\n const { result: stacktrace, alreadyRewritten } = ssrRewriteStacktrace(\n e.stack,\n moduleGraph,\n )\n rebindErrorStacktrace(e, stacktrace)\n if (alreadyRewritten) {\n e.message +=\n ' (The stacktrace appears to be already rewritten by something else, but was passed to vite.ssrFixStacktrace. This may cause incorrect stacktraces.)'\n }\n\n rewroteStacktraces.add(e)\n}", "messages": null, "tools": null} {"id": "9066199837f3311d", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/node/__tests_dts__/config.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 2791, "sha256": "67f262872905a4aa95afb59e97a872e32e6d1bbc1ad8e4cdf78537e6039e8452", "text": "/* eslint-disable @typescript-eslint/ban-ts-comment */\n/* eslint-disable @typescript-eslint/no-unused-vars */\nimport type { Equal, ExpectTrue } from '@type-challenges/utils'\nimport {\n type UserConfig,\n type UserConfigExport,\n type UserConfigFn,\n type UserConfigFnObject,\n type UserConfigFnPromise,\n defineConfig,\n} from '../config'\nimport { mergeConfig } from '../utils'\n\nconst configObjectDefined = defineConfig({})\nconst configObjectPromiseDefined = defineConfig(Promise.resolve({}))\nconst configFnObjectDefined = defineConfig(() => ({}))\nconst configFnPromiseDefined = defineConfig(async () => ({}))\nconst configFnDefined = defineConfig(() =>\n // TypeScript requires both non-promise config and\n // promise config to have at least one property\n Math.random() > 0.5 ? { base: '' } : Promise.resolve({ base: '/' }),\n)\nconst configExportDefined = defineConfig({} as UserConfigExport)\n\nexport type cases1 = [\n ExpectTrue>,\n ExpectTrue>>,\n ExpectTrue>,\n ExpectTrue>,\n ExpectTrue>,\n ExpectTrue>,\n]\n\ndefineConfig({\n base: '',\n build: {\n minify: 'oxc', // `as const` is not needed\n },\n server: {\n proxy: {\n '/test': {\n bypass: () => false,\n },\n },\n },\n // @ts-expect-error --- invalid option should error\n unknownProperty: 1,\n})\n\ndefineConfig(() => ({\n base: '',\n build: {\n minify: 'oxc' as const, // ideally we don't want to require `as const` here\n },\n server: {\n proxy: {\n '/test': {\n bypass: () => false as const, // ideally we don't want to require `as const` here\n },\n },\n },\n unknownProperty: 1, // we cannot catch invalid option for this case, ideally we should\n}))\n\n// @ts-expect-error --- nested invalid option `build.unknown` should error\ndefineConfig(() => ({\n base: '',\n build: {\n unknown: 1,\n },\n}))\n\ndefineConfig(async () => ({\n base: '',\n build: {\n minify: 'oxc' as const, // ideally we don't want to require `as const` here\n },\n server: {\n proxy: {\n '/test': {\n bypass: () => false as const, // ideally we don't want to require `as const` here\n },\n },\n },\n unknownProperty: 1, // we cannot catch invalid option for this case, ideally we should\n}))\n\n// @ts-expect-error --- nested invalid option `build.unknown` should error\ndefineConfig(async () => ({\n base: '',\n build: {\n unknown: 1,\n },\n}))\n\nmergeConfig(defineConfig({}), defineConfig({}))\nmergeConfig(\n // @ts-expect-error\n defineConfig(() => ({})),\n defineConfig({}),\n)\n\nexport {}", "messages": null, "tools": null} {"id": "90c38ca8e2a8be13", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "include/nlohmann/detail/output/serializer.hpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 41379, "sha256": "520adbb890c77ed0507819f324cb98a071495aacbc1ad43c2d4a369f1aa9703d", "text": "// __ _____ _____ _____\n// __| | __| | | | JSON for Modern C++\n// | | |__ | | | | | | version 3.12.0\n// |_____|_____|_____|_|___| https://github.com/nlohmann/json\n//\n// SPDX-FileCopyrightText: 2008, 2009 Björn Hoehrmann \n// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann \n// SPDX-License-Identifier: MIT\n\n#pragma once\n\n#include // reverse, remove, fill, find, none_of\n#include // array\n#include // localeconv, lconv\n#include // labs, isfinite, isnan, signbit\n#include // size_t, ptrdiff_t\n#include // uint8_t\n#include // snprintf\n#include // numeric_limits\n#include // string, char_traits\n#include // setfill, setw\n#include // is_same\n#include // move\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nNLOHMANN_JSON_NAMESPACE_BEGIN\nnamespace detail\n{\n\n///////////////////\n// serialization //\n///////////////////\n\n/// how to treat decoding errors\nenum class error_handler_t\n{\n strict, ///< throw a type_error exception in case of invalid UTF-8\n replace, ///< replace invalid UTF-8 sequences with U+FFFD\n ignore ///< ignore invalid UTF-8 sequences\n};\n\ntemplate\nclass serializer\n{\n using string_t = typename BasicJsonType::string_t;\n using number_float_t = typename BasicJsonType::number_float_t;\n using number_integer_t = typename BasicJsonType::number_integer_t;\n using number_unsigned_t = typename BasicJsonType::number_unsigned_t;\n using binary_char_t = typename BasicJsonType::binary_t::value_type;\n static constexpr std::uint8_t UTF8_ACCEPT = 0;\n static constexpr std::uint8_t UTF8_REJECT = 1;\n\n public:\n /*!\n @param[in] s output stream to serialize to\n @param[in] ichar indentation character to use\n @param[in] error_handler_ how to react on decoding errors\n */\n serializer(output_adapter_t s, const char ichar,\n error_handler_t error_handler_ = error_handler_t::strict)\n : o(std::move(s))\n , loc(std::localeconv())\n , thousands_sep(loc->thousands_sep == nullptr ? '\\0' : std::char_traits::to_char_type(* (loc->thousands_sep)))\n , decimal_point(loc->decimal_point == nullptr ? '\\0' : std::char_traits::to_char_type(* (loc->decimal_point)))\n , indent_char(ichar)\n , indent_string(512, indent_char)\n , error_handler(error_handler_)\n {}\n\n // deleted because of pointer members\n serializer(const serializer&) = delete;\n serializer& operator=(const serializer&) = delete;\n serializer(serializer&&) = delete;\n serializer& operator=(serializer&&) = delete;\n ~serializer() = default;\n\n /*!\n @brief internal implementation of the serialization function\n\n This function is called by the public member function dump and organizes\n the serialization internally. The indentation level is propagated as\n additional parameter. In case of arrays and objects, the function is\n called recursively.\n\n - strings and object keys are escaped using `escape_string()`\n - integer numbers are converted implicitly via `operator<<`\n - floating-point numbers are converted to a string using `\"%g\"` format\n - binary values are serialized as objects containing the subtype and the\n byte array\n\n @param[in] val value to serialize\n @param[in] pretty_print whether the output shall be pretty-printed\n @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters\n in the output are escaped with `\\uXXXX` sequences, and the result consists\n of ASCII characters only.\n @param[in] indent_step the indent level\n @param[in] current_indent the current indent level (only used internally)\n */\n void dump(const BasicJsonType& val,\n const bool pretty_print,\n const bool ensure_ascii,\n const unsigned int indent_step,\n const unsigned int current_indent = 0)\n {\n switch (val.m_data.m_type)\n {\n case value_t::object:\n {\n if (val.m_data.m_value.object->empty())\n {\n o->write_characters(\"{}\", 2);\n return;\n }\n\n if (pretty_print)\n {\n o->write_characters(\"{\\n\", 2);\n\n // variable to hold indentation for recursive calls\n const auto new_indent = current_indent + indent_step;\n if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))\n {\n indent_string.resize(indent_string.size() * 2, ' ');\n }\n\n // first n-1 elements\n auto i = val.m_data.m_value.object->cbegin();\n for (std::size_t cnt = 0; cnt < val.m_data.m_value.object->size() - 1; ++cnt, ++i)\n {\n o->write_characters(indent_string.c_str(), new_indent);\n o->write_character('\\\"');\n dump_escaped(i->first, ensure_ascii);\n o->write_characters(\"\\\": \", 3);\n dump(i->second, true, ensure_ascii, indent_step, new_indent);\n o->write_characters(\",\\n\", 2);\n }\n\n // last element\n JSON_ASSERT(i != val.m_data.m_value.object->cend());\n JSON_ASSERT(std::next(i) == val.m_data.m_value.object->cend());\n o->write_characters(indent_string.c_str(), new_indent);\n o->write_character('\\\"');\n dump_escaped(i->first, ensure_ascii);\n o->write_characters(\"\\\": \", 3);\n dump(i->second, true, ensure_ascii, indent_step, new_indent);\n\n o->write_character('\\n');\n o->write_characters(indent_string.c_str(), current_indent);\n o->write_character('}');\n }\n else\n {\n o->write_character('{');\n\n // first n-1 elements\n auto i = val.m_data.m_value.object->cbegin();\n for (std::size_t cnt = 0; cnt < val.m_data.m_value.object->size() - 1; ++cnt, ++i)\n {\n o->write_character('\\\"');\n dump_escaped(i->first, ensure_ascii);\n o->write_characters(\"\\\":\", 2);\n dump(i->second, false, ensure_ascii, indent_step, current_indent);\n o->write_character(',');\n }\n\n // last element\n JSON_ASSERT(i != val.m_data.m_value.object->cend());\n JSON_ASSERT(std::next(i) == val.m_data.m_value.object->cend());\n o->write_character('\\\"');\n dump_escaped(i->first, ensure_ascii);\n o->write_characters(\"\\\":\", 2);\n dump(i->second, false, ensure_ascii, indent_step, current_indent);\n\n o->write_character('}');\n }\n\n return;\n }\n\n case value_t::array:\n {\n if (val.m_data.m_value.array->empty())\n {\n o->write_characters(\"[]\", 2);\n return;\n }\n\n if (pretty_print)\n {\n o->write_characters(\"[\\n\", 2);\n\n // variable to hold indentation for recursive calls\n const auto new_indent = current_indent + indent_step;\n if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))\n {\n indent_string.resize(indent_string.size() * 2, ' ');\n }\n\n // first n-1 elements\n for (auto i = val.m_data.m_value.array->cbegin();\n i != val.m_data.m_value.array->cend() - 1; ++i)\n {\n o->write_characters(indent_string.c_str(), new_indent);\n dump(*i, true, ensure_ascii, indent_step, new_indent);\n o->write_characters(\",\\n\", 2);\n }\n\n // last element\n JSON_ASSERT(!val.m_data.m_value.array->empty());\n o->write_characters(indent_string.c_str(), new_indent);\n dump(val.m_data.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);\n\n o->write_character('\\n');\n o->write_characters(indent_string.c_str(), current_indent);\n o->write_character(']');\n }\n else\n {\n o->write_character('[');\n\n // first n-1 elements\n for (auto i = val.m_data.m_value.array->cbegin();\n i != val.m_data.m_value.array->cend() - 1; ++i)\n {\n dump(*i, false, ensure_ascii, indent_step, current_indent);\n o->write_character(',');\n }\n\n // last element\n JSON_ASSERT(!val.m_data.m_value.array->empty());\n dump(val.m_data.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);\n\n o->write_character(']');\n }\n\n return;\n }\n\n case value_t::string:\n {\n o->write_character('\\\"');\n dump_escaped(*val.m_data.m_value.string, ensure_ascii);\n o->write_character('\\\"');\n return;\n }\n\n case value_t::binary:\n {\n if (pretty_print)\n {\n o->write_characters(\"{\\n\", 2);\n\n // variable to hold indentation for recursive calls\n const auto new_indent = current_indent + indent_step;\n if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))\n {\n indent_string.resize(indent_string.size() * 2, ' ');\n }\n\n o->write_characters(indent_string.c_str(), new_indent);\n\n o->write_characters(\"\\\"bytes\\\": [\", 10);\n\n if (!val.m_data.m_value.binary->empty())\n {\n for (auto i = val.m_data.m_value.binary->cbegin();\n i != val.m_data.m_value.binary->cend() - 1; ++i)\n {\n dump_integer(*i);\n o->write_characters(\", \", 2);\n }\n dump_integer(val.m_data.m_value.binary->back());\n }\n\n o->write_characters(\"],\\n\", 3);\n o->write_characters(indent_string.c_str(), new_indent);\n\n o->write_characters(\"\\\"subtype\\\": \", 11);\n if (val.m_data.m_value.binary->has_subtype())\n {\n dump_integer(val.m_data.m_value.binary->subtype());\n }\n else\n {\n o->write_characters(\"null\", 4);\n }\n o->write_character('\\n');\n o->write_characters(indent_string.c_str(), current_indent);\n o->write_character('}');\n }\n else\n {\n o->write_characters(\"{\\\"bytes\\\":[\", 10);\n\n if (!val.m_data.m_value.binary->empty())\n {\n for (auto i = val.m_data.m_value.binary->cbegin();\n i != val.m_data.m_value.binary->cend() - 1; ++i)\n {\n dump_integer(*i);\n o->write_character(',');\n }\n dump_integer(val.m_data.m_value.binary->back());\n }\n\n o->write_characters(\"],\\\"subtype\\\":\", 12);\n if (val.m_data.m_value.binary->has_subtype())\n {\n dump_integer(val.m_data.m_value.binary->subtype());\n o->write_character('}');\n }\n else\n {\n o->write_characters(\"null}\", 5);\n }\n }\n return;\n }\n\n case value_t::boolean:\n {\n if (val.m_data.m_value.boolean)\n {\n o->write_characters(\"true\", 4);\n }\n else\n {\n o->write_characters(\"false\", 5);\n }\n return;\n }\n\n case value_t::number_integer:\n {\n dump_integer(val.m_data.m_value.number_integer);\n return;\n }\n\n case value_t::number_unsigned:\n {\n dump_integer(val.m_data.m_value.number_unsigned);\n return;\n }\n\n case value_t::number_float:\n {\n dump_float(val.m_data.m_value.number_float);\n return;\n }\n\n case value_t::discarded:\n {\n o->write_characters(\"\", 11);\n return;\n }\n\n case value_t::null:\n {\n o->write_characters(\"null\", 4);\n return;\n }\n\n default: // LCOV_EXCL_LINE\n JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE\n }\n }\n\n JSON_PRIVATE_UNLESS_TESTED:\n /*!\n @brief dump escaped string\n\n Escape a string by replacing certain special characters by a sequence of an\n escape character (backslash) and another character and other control\n characters by a sequence of \"\\u\" followed by a four-digit hex\n representation. The escaped string is written to output stream @a o.\n\n @param[in] s the string to escape\n @param[in] ensure_ascii whether to escape non-ASCII characters with\n \\uXXXX sequences\n\n @complexity Linear in the length of string @a s.\n */\n void dump_escaped(const string_t& s, const bool ensure_ascii)\n {\n std::uint32_t codepoint{};\n std::uint8_t state = UTF8_ACCEPT;\n std::size_t bytes = 0; // number of bytes written to string_buffer\n\n // number of bytes written at the point of the last valid byte\n std::size_t bytes_after_last_accept = 0;\n std::size_t undumped_chars = 0;\n\n for (std::size_t i = 0; i < s.size(); ++i)\n {\n const auto byte = static_cast(s[i]);\n\n switch (decode(state, codepoint, byte))\n {\n case UTF8_ACCEPT: // decode found a new code point\n {\n switch (codepoint)\n {\n case 0x08: // backspace\n {\n string_buffer[bytes++] = '\\\\';\n string_buffer[bytes++] = 'b';\n break;\n }\n\n case 0x09: // horizontal tab\n {\n string_buffer[bytes++] = '\\\\';\n string_buffer[bytes++] = 't';\n break;\n }\n\n case 0x0A: // newline\n {\n string_buffer[bytes++] = '\\\\';\n string_buffer[bytes++] = 'n';\n break;\n }\n\n case 0x0C: // formfeed\n {\n string_buffer[bytes++] = '\\\\';\n string_buffer[bytes++] = 'f';\n break;\n }\n\n case 0x0D: // carriage return\n {\n string_buffer[bytes++] = '\\\\';\n string_buffer[bytes++] = 'r';\n break;\n }\n\n case 0x22: // quotation mark\n {\n string_buffer[bytes++] = '\\\\';\n string_buffer[bytes++] = '\\\"';\n break;\n }\n\n case 0x5C: // reverse solidus\n {\n string_buffer[bytes++] = '\\\\';\n string_buffer[bytes++] = '\\\\';\n break;\n }\n\n default:\n {\n // escape control characters (0x00..0x1F) or, if\n // ensure_ascii parameter is used, non-ASCII characters\n if ((codepoint <= 0x1F) || (ensure_ascii && (codepoint >= 0x7F)))\n {\n if (codepoint <= 0xFFFF)\n {\n write_u_escape(bytes, static_cast(codepoint));\n }\n else\n {\n write_u_escape(bytes, static_cast(0xD7C0u + (codepoint >> 10u)));\n write_u_escape(bytes, static_cast(0xDC00u + (codepoint & 0x3FFu)));\n }\n }\n else\n {\n // copy byte to buffer (all previous bytes\n // been copied have in default case above)\n string_buffer[bytes++] = s[i];\n }\n break;\n }\n }\n\n // write buffer and reset index; there must be 13 bytes\n // left, as this is the maximal number of bytes to be\n // written (\"\\uxxxx\\uxxxx\\0\") for one code point\n if (string_buffer.size() - bytes < 13)\n {\n o->write_characters(string_buffer.data(), bytes);\n bytes = 0;\n }\n\n // remember the byte position of this accept\n bytes_after_last_accept = bytes;\n undumped_chars = 0;\n break;\n }\n\n case UTF8_REJECT: // decode found invalid UTF-8 byte\n {\n switch (error_handler)\n {\n case error_handler_t::strict:\n {\n JSON_THROW(type_error::create(316, concat(\"invalid UTF-8 byte at index \", std::to_string(i), \": 0x\", hex_bytes(byte | 0)), nullptr));\n }\n\n case error_handler_t::ignore:\n case error_handler_t::replace:\n {\n // in case we saw this character the first time, we\n // would like to read it again, because the byte\n // may be OK for itself, but just not OK for the\n // previous sequence\n if (undumped_chars > 0)\n {\n --i;\n }\n\n // reset length buffer to the last accepted index;\n // thus removing/ignoring the invalid characters\n bytes = bytes_after_last_accept;\n\n if (error_handler == error_handler_t::replace)\n {\n // add a replacement character\n if (ensure_ascii)\n {\n string_buffer[bytes++] = '\\\\';\n string_buffer[bytes++] = 'u';\n string_buffer[bytes++] = 'f';\n string_buffer[bytes++] = 'f';\n string_buffer[bytes++] = 'f';\n string_buffer[bytes++] = 'd';\n }\n else\n {\n string_buffer[bytes++] = detail::binary_writer::to_char_type('\\xEF');\n string_buffer[bytes++] = detail::binary_writer::to_char_type('\\xBF');\n string_buffer[bytes++] = detail::binary_writer::to_char_type('\\xBD');\n }\n\n // write buffer and reset index; there must be 13 bytes\n // left, as this is the maximal number of bytes to be\n // written (\"\\uxxxx\\uxxxx\\0\") for one code point\n if (string_buffer.size() - bytes < 13)\n {\n o->write_characters(string_buffer.data(), bytes);\n bytes = 0;\n }\n\n bytes_after_last_accept = bytes;\n }\n\n undumped_chars = 0;\n\n // continue processing the string\n state = UTF8_ACCEPT;\n break;\n }\n\n default: // LCOV_EXCL_LINE\n JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE\n }\n break;\n }\n\n default: // decode found yet incomplete multibyte code point\n {\n if (!ensure_ascii)\n {\n // code point will not be escaped - copy byte to buffer\n string_buffer[bytes++] = s[i];\n }\n ++undumped_chars;\n break;\n }\n }\n }\n\n // we finished processing the string\n if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT))\n {\n // write buffer\n if (bytes > 0)\n {\n o->write_characters(string_buffer.data(), bytes);\n }\n }\n else\n {\n // we finish reading, but do not accept: string was incomplete\n switch (error_handler)\n {\n case error_handler_t::strict:\n {\n JSON_THROW(type_error::create(316, concat(\"incomplete UTF-8 string; last byte: 0x\", hex_bytes(static_cast(s.back() | 0))), nullptr));\n }\n\n case error_handler_t::ignore:\n {\n // write all accepted bytes\n o->write_characters(string_buffer.data(), bytes_after_last_accept);\n break;\n }\n\n case error_handler_t::replace:\n {\n // write all accepted bytes\n o->write_characters(string_buffer.data(), bytes_after_last_accept);\n // add a replacement character\n if (ensure_ascii)\n {\n o->write_characters(\"\\\\ufffd\", 6);\n }\n else\n {\n o->write_characters(\"\\xEF\\xBF\\xBD\", 3);\n }\n break;\n }\n\n default: // LCOV_EXCL_LINE\n JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE\n }\n }\n }\n\n private:\n /*!\n @brief count digits\n\n Count the number of decimal (base 10) digits for an input unsigned integer.\n\n @param[in] x unsigned integer number to count its digits\n @return number of decimal digits\n */\n unsigned int count_digits(number_unsigned_t x) noexcept\n {\n unsigned int n_digits = 1;\n for (;;)\n {\n if (x < 10)\n {\n return n_digits;\n }\n if (x < 100)\n {\n return n_digits + 1;\n }\n if (x < 1000)\n {\n return n_digits + 2;\n }\n if (x < 10000)\n {\n return n_digits + 3;\n }\n x = x / 10000u;\n n_digits += 4;\n }\n }\n\n /*!\n * @brief convert a byte to a uppercase hex representation\n * @param[in] byte byte to represent\n * @return representation (\"00\"..\"FF\")\n */\n static std::string hex_bytes(std::uint8_t byte)\n {\n std::string result = \"FF\";\n constexpr const char* nibble_to_hex = \"0123456789ABCDEF\";\n result[0] = nibble_to_hex[byte / 16];\n result[1] = nibble_to_hex[byte % 16];\n return result;\n }\n\n /*!\n * @brief write a lowercase \"\\uXXXX\" escape sequence into @a string_buffer\n *\n * Branch-free replacement for `snprintf(buf, 7, \"\\\\u%04x\", codeunit)` in the\n * string escaping hot path. It writes exactly six characters ('\\\\', 'u' and\n * four hex digits) at position @a pos of @a string_buffer via a nibble\n * lookup table, avoiding the format-string parsing and locale machinery of\n * `snprintf`. Advances @a pos by the number of bytes written (6).\n *\n * @param[in] pos position in @a string_buffer to write at; there must\n * be at least 6 bytes of headroom\n * @param[in] codeunit 16-bit value to encode\n */\n void write_u_escape(std::size_t& pos, std::uint16_t codeunit) noexcept\n {\n JSON_ASSERT(string_buffer.size() - pos >= 6);\n constexpr const char* nibble_to_hex = \"0123456789abcdef\";\n string_buffer[pos + 0] = '\\\\';\n string_buffer[pos + 1] = 'u';\n string_buffer[pos + 2] = nibble_to_hex[(codeunit >> 12u) & 0x0Fu];\n string_buffer[pos + 3] = nibble_to_hex[(codeunit >> 8u) & 0x0Fu];\n string_buffer[pos + 4] = nibble_to_hex[(codeunit >> 4u) & 0x0Fu];\n string_buffer[pos + 5] = nibble_to_hex[codeunit & 0x0Fu];\n pos += 6;\n }\n\n // templates to avoid warnings about useless casts\n template ::value, int> = 0>\n bool is_negative_number(NumberType x)\n {\n return x < 0;\n }\n\n template < typename NumberType, enable_if_t ::value, int > = 0 >\n bool is_negative_number(NumberType /*unused*/)\n {\n return false;\n }\n\n /*!\n @brief dump an integer\n\n Dump a given integer to output stream @a o. Works internally with\n @a number_buffer.\n\n @param[in] x integer number (signed or unsigned) to dump\n @tparam NumberType either @a number_integer_t or @a number_unsigned_t\n */\n template < typename NumberType, detail::enable_if_t <\n std::is_integral::value ||\n std::is_same::value ||\n std::is_same::value ||\n std::is_same::value,\n int > = 0 >\n void dump_integer(NumberType x)\n {\n static constexpr std::array, 100> digits_to_99\n {\n {\n {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}},\n {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}},\n {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}},\n {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}},\n {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}},\n {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}},\n {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}},\n {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}},\n {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}},\n {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}},\n }\n };\n\n // special case for \"0\"\n if (x == 0)\n {\n o->write_character('0');\n return;\n }\n\n // use a pointer to fill the buffer\n auto buffer_ptr = number_buffer.begin(); // NOLINT(llvm-qualified-auto,readability-qualified-auto,cppcoreguidelines-pro-type-vararg,hicpp-vararg)\n\n number_unsigned_t abs_value;\n\n unsigned int n_chars{};\n\n if (is_negative_number(x))\n {\n *buffer_ptr = '-';\n abs_value = remove_sign(static_cast(x));\n\n // account one more byte for the minus sign\n n_chars = 1 + count_digits(abs_value);\n }\n else\n {\n abs_value = static_cast(x);\n n_chars = count_digits(abs_value);\n }\n\n // spare 1 byte for '\\0'\n JSON_ASSERT(n_chars < number_buffer.size() - 1);\n\n // jump to the end to generate the string from backward,\n // so we later avoid reversing the result\n buffer_ptr += static_cast(n_chars);\n\n // Fast int2ascii implementation inspired by \"Fastware\" talk by Andrei Alexandrescu\n // See: https://www.youtube.com/watch?v=o4-CwDo2zpg\n while (abs_value >= 100)\n {\n const auto digits_index = static_cast((abs_value % 100));\n abs_value /= 100;\n *(--buffer_ptr) = digits_to_99[digits_index][1];\n *(--buffer_ptr) = digits_to_99[digits_index][0];\n }\n\n if (abs_value >= 10)\n {\n const auto digits_index = static_cast(abs_value);\n *(--buffer_ptr) = digits_to_99[digits_index][1];\n *(--buffer_ptr) = digits_to_99[digits_index][0];\n }\n else\n {\n *(--buffer_ptr) = static_cast('0' + abs_value);\n }\n\n o->write_characters(number_buffer.data(), n_chars);\n }\n\n /*!\n @brief dump a floating-point number\n\n Dump a given floating-point number to output stream @a o. Works internally\n with @a number_buffer.\n\n @param[in] x floating-point number to dump\n */\n void dump_float(number_float_t x)\n {\n // NaN / inf\n if (!std::isfinite(x))\n {\n o->write_characters(\"null\", 4);\n return;\n }\n\n // If number_float_t is an IEEE-754 single or double precision number,\n // use the Grisu2 algorithm to produce short numbers which are\n // guaranteed to round-trip, using strtof and strtod, resp.\n //\n // NB: The test below works if == .\n static constexpr bool is_ieee_single_or_double\n = (std::numeric_limits::is_iec559 && std::numeric_limits::digits == 24 && std::numeric_limits::max_exponent == 128) ||\n (std::numeric_limits::is_iec559 && std::numeric_limits::digits == 53 && std::numeric_limits::max_exponent == 1024);\n\n dump_float(x, std::integral_constant());\n }\n\n void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)\n {\n auto* begin = number_buffer.data();\n auto* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);\n\n o->write_characters(begin, static_cast(end - begin));\n }\n\n JSON_HEDLEY_NON_NULL(1)\n static int snprintf_float(char* buf, std::size_t size, int d, double x)\n {\n // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)\n return (std::snprintf)(buf, size, \"%.*g\", d, x);\n }\n\n JSON_HEDLEY_NON_NULL(1)\n static int snprintf_float(char* buf, std::size_t size, int d, long double x)\n {\n // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg)\n return (std::snprintf)(buf, size, \"%.*Lg\", d, x);\n }\n\n void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)\n {\n // get the number of digits for a float -> text -> float round-trip\n static constexpr auto d = std::numeric_limits::max_digits10;\n\n // the actual conversion\n std::ptrdiff_t len = snprintf_float(number_buffer.data(), number_buffer.size(), d, x);\n\n // negative value indicates an error\n JSON_ASSERT(len > 0);\n // check if the buffer was large enough\n JSON_ASSERT(static_cast(len) < number_buffer.size());\n\n // erase thousands separators\n if (thousands_sep != '\\0')\n {\n // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::remove returns an iterator, see https://github.com/nlohmann/json/issues/3081\n const auto end = std::remove(number_buffer.begin(), number_buffer.begin() + len, thousands_sep);\n std::fill(end, number_buffer.end(), '\\0');\n JSON_ASSERT((end - number_buffer.begin()) <= len);\n len = (end - number_buffer.begin());\n }\n\n // convert decimal point to '.'\n if (decimal_point != '\\0' && decimal_point != '.')\n {\n // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::find returns an iterator, see https://github.com/nlohmann/json/issues/3081\n const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);\n if (dec_pos != number_buffer.end())\n {\n *dec_pos = '.';\n }\n }\n\n o->write_characters(number_buffer.data(), static_cast(len));\n\n // determine if we need to append \".0\"\n const bool value_is_int_like =\n std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,\n [](char c)\n {\n return c == '.' || c == 'e';\n });\n\n if (value_is_int_like)\n {\n o->write_characters(\".0\", 2);\n }\n }\n\n /*!\n @brief check whether a string is UTF-8 encoded\n\n The function checks each byte of a string whether it is UTF-8 encoded. The\n result of the check is stored in the @a state parameter. The function must\n be called initially with state 0 (accept). State 1 means the string must\n be rejected, because the current byte is not allowed. If the string is\n completely processed, but the state is non-zero, the string ended\n prematurely; that is, the last byte indicated more bytes should have\n followed.\n\n @param[in,out] state the state of the decoding\n @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)\n @param[in] byte next byte to decode\n @return new state\n\n @note The function has been edited: a std::array is used.\n\n @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann \n @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/\n */\n static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept\n {\n static const std::array utf8d =\n {\n {\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1F\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3F\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5F\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7F\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9F\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // A0..BF\n 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0..DF\n 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF\n 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF\n 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2\n 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4\n 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6\n 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8\n }\n };\n\n JSON_ASSERT(static_cast(byte) < utf8d.size());\n const std::uint8_t type = utf8d[byte];\n\n codep = (state != UTF8_ACCEPT)\n ? (byte & 0x3fu) | (codep << 6u)\n : (0xFFu >> type) & (byte);\n\n const std::size_t index = 256u + (static_cast(state) * 16u) + static_cast(type);\n JSON_ASSERT(index < utf8d.size());\n state = utf8d[index];\n return state;\n }\n\n /*\n * Overload to make the compiler happy while it is instantiating\n * dump_integer for number_unsigned_t.\n * Must never be called.\n */\n number_unsigned_t remove_sign(number_unsigned_t x)\n {\n JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE\n return x; // LCOV_EXCL_LINE\n }\n\n /*\n * Helper function for dump_integer\n *\n * This function takes a negative signed integer and returns its absolute\n * value as an unsigned integer. The plus/minus shuffling is necessary as we\n * cannot directly remove the sign of an arbitrary signed integer as the\n * absolute values of INT_MIN and INT_MAX are usually not the same. See\n * #1708 for details.\n */\n number_unsigned_t remove_sign(number_integer_t x) noexcept\n {\n JSON_ASSERT(x < 0 && x < (std::numeric_limits::max)()); // NOLINT(misc-redundant-expression)\n return static_cast(-(x + 1)) + 1;\n }\n\n private:\n /// the output of the serializer\n output_adapter_t o = nullptr;\n\n /// a (hopefully) large enough character buffer\n std::array number_buffer{{}};\n\n /// the locale\n const std::lconv* loc = nullptr;\n /// the locale's thousand separator character\n const char thousands_sep = '\\0';\n /// the locale's decimal point character\n const char decimal_point = '\\0';\n\n /// string buffer\n std::array string_buffer{{}};\n\n /// the indentation character\n const char indent_char;\n /// the indentation string\n string_t indent_string;\n\n /// error_handler how to react on decoding errors\n const error_handler_t error_handler;\n};\n\n} // namespace detail\nNLOHMANN_JSON_NAMESPACE_END", "messages": null, "tools": null} {"id": "915fc3f9e2609dfe", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/operator_ltlt__basic_json.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 548, "sha256": "3841c0bfb9fe04b8a69e5cdba29a5108d8f0afb996d4799b76f3933c3a62f4de", "text": "#include \n#include \n#include \n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n\n // serialize without indentation\n std::cout << j_object << \"\\n\\n\";\n std::cout << j_array << \"\\n\\n\";\n\n // serialize with indentation\n std::cout << std::setw(4) << j_object << \"\\n\\n\";\n std::cout << std::setw(2) << j_array << \"\\n\\n\";\n std::cout << std::setw(1) << std::setfill('\\t') << j_object << \"\\n\\n\";\n}", "messages": null, "tools": null} {"id": "91ee92051b00c426", "category": "code", "domain": "code", "source": "serde", "license": "MIT OR Apache-2.0", "license_url": "https://spdx.org/licenses/MIT.html", "path": "serde_derive/src/internals/respan.rs", "lang": "rust", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/serde-rs/serde", "commit": "747814f7d5fbab872df3b02f070c165b91bde062", "collector": "tools/harvest.py"}, "chars": 450, "sha256": "ad954b93d61fdb2c445347b7236045413e6cdd8d701e8e3b0e8be5ccfaee2caa", "text": "use proc_macro2::{Group, Span, TokenStream, TokenTree};\n\npub(crate) fn respan(stream: TokenStream, span: Span) -> TokenStream {\n stream\n .into_iter()\n .map(|token| respan_token(token, span))\n .collect()\n}\n\nfn respan_token(mut token: TokenTree, span: Span) -> TokenTree {\n if let TokenTree::Group(g) = &mut token {\n *g = Group::new(g.delimiter(), respan(g.stream(), span));\n }\n token.set_span(span);\n token\n}", "messages": null, "tools": null} {"id": "92992e4ae5508457", "category": "code", "domain": "code", "source": "flask", "license": "BSD-3-Clause", "license_url": "https://spdx.org/licenses/BSD-3-Clause.html", "path": "tests/test_converters.py", "lang": "python", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/pallets/flask", "commit": "6a2f545bfd8ed31e19066a299296917e034aca58", "collector": "tools/harvest.py"}, "chars": 1092, "sha256": "ef26e4ef7d93a15164988334c6588c455fa4b1151a76b9d7a1a03382ca4f3e7f", "text": "from werkzeug.routing import BaseConverter\n\nfrom flask import request\nfrom flask import session\nfrom flask import url_for\n\n\ndef test_custom_converters(app, client):\n class ListConverter(BaseConverter):\n def to_python(self, value):\n return value.split(\",\")\n\n def to_url(self, value):\n base_to_url = super().to_url\n return \",\".join(base_to_url(x) for x in value)\n\n app.url_map.converters[\"list\"] = ListConverter\n\n @app.route(\"/\")\n def index(args):\n return \"|\".join(args)\n\n assert client.get(\"/1,2,3\").data == b\"1|2|3\"\n\n with app.test_request_context():\n assert url_for(\"index\", args=[4, 5, 6]) == \"/4,5,6\"\n\n\ndef test_context_available(app, client):\n class ContextConverter(BaseConverter):\n def to_python(self, value):\n assert request is not None\n assert session is not None\n return value\n\n app.url_map.converters[\"ctx\"] = ContextConverter\n\n @app.get(\"/\")\n def index(name):\n return name\n\n assert client.get(\"/admin\").data == b\"admin\"", "messages": null, "tools": null} {"id": "92a0441fee91e074", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/ssr-pug/server.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 1875, "sha256": "c2b0c07a640c1d88fc64211d5f9cb2602d8eaee5e1e9e54bc7c7f617a01f51c0", "text": "// @ts-check\nimport path from 'node:path'\nimport pug from 'pug'\nimport express from 'express'\n\nconst isTest = process.env.VITEST\n\nconst DYNAMIC_SCRIPTS = `\n \n \n`\n\nexport async function createServer(root = process.cwd(), hmrPort) {\n const resolve = (p) => path.resolve(import.meta.dirname, p)\n\n const app = express()\n\n /**\n * @type {import('vite').ViteDevServer}\n */\n const vite = await (\n await import('vite')\n ).createServer({\n root,\n logLevel: isTest ? 'error' : 'info',\n server: {\n middlewareMode: true,\n watch: {\n // During tests we edit the files too fast and sometimes chokidar\n // misses change events, so enforce polling for consistency\n usePolling: true,\n interval: 100,\n },\n hmr: {\n port: hmrPort,\n },\n },\n appType: 'custom',\n })\n // use vite's connect instance as middleware\n app.use(vite.middlewares)\n\n app.use('*all', async (req, res) => {\n try {\n let [url] = req.originalUrl.split('?')\n url = url.replace(/\\.html$/, '.pug')\n if (url.endsWith('/')) url += 'index.pug'\n\n const htmlLoc = resolve(`.${url}`)\n let html = pug.renderFile(htmlLoc)\n html = html.replace('', `${DYNAMIC_SCRIPTS}`)\n html = await vite.transformIndexHtml(url, html)\n\n res.status(200).set({ 'Content-Type': 'text/html' }).end(html)\n } catch (e) {\n vite && vite.ssrFixStacktrace(e)\n console.log(e.stack)\n res.status(500).end(e.stack)\n }\n })\n\n return { app, vite }\n}\n\nif (!isTest) {\n createServer().then(({ app }) =>\n app.listen(5173, () => {\n console.log('http://localhost:5173')\n }),\n )\n}", "messages": null, "tools": null} {"id": "92b189de9a68c92d", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/format_as.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 346, "sha256": "4cf3dbbaf7f095a01b3e56fcaba512fcbd14eb0cee272f19bd3afbd8546e37b9", "text": "#include \n#include \n\nusing json = nlohmann::json;\n\nint main()\n{\n // create a JSON value\n json j = {{\"one\", 1}, {\"two\", 2}};\n\n // format_as() is found via argument-dependent lookup, the same way\n // fmt::format/fmt::print would find it\n auto j_str = format_as(j);\n\n std::cout << j_str << std::endl;\n}", "messages": null, "tools": null} {"id": "92b4d3492a8dea6f", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/is_primitive.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 990, "sha256": "43a90a793a805b3fe0842691472709fbf56d88d5d20ec77c35ba000bbd411d66", "text": "#include \n#include \n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_float = 23.42;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_primitive()\n std::cout << std::boolalpha;\n std::cout << j_null.is_primitive() << '\\n';\n std::cout << j_boolean.is_primitive() << '\\n';\n std::cout << j_number_integer.is_primitive() << '\\n';\n std::cout << j_number_unsigned_integer.is_primitive() << '\\n';\n std::cout << j_number_float.is_primitive() << '\\n';\n std::cout << j_object.is_primitive() << '\\n';\n std::cout << j_array.is_primitive() << '\\n';\n std::cout << j_string.is_primitive() << '\\n';\n std::cout << j_binary.is_primitive() << '\\n';\n}", "messages": null, "tools": null} {"id": "936f693b7db2feba", "category": "code", "domain": "code", "source": "flask", "license": "BSD-3-Clause", "license_url": "https://spdx.org/licenses/BSD-3-Clause.html", "path": "tests/test_basic.py", "lang": "python", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/pallets/flask", "commit": "6a2f545bfd8ed31e19066a299296917e034aca58", "collector": "tools/harvest.py"}, "chars": 54098, "sha256": "294b7a62b71adc9c68b44db200ba3d8fc24c8e02437e736e15ba58903735814c", "text": "import gc\nimport importlib.metadata\nimport re\nimport typing as t\nimport uuid\nimport weakref\nfrom contextlib import nullcontext\nfrom datetime import datetime\nfrom datetime import timezone\nfrom platform import python_implementation\n\nimport pytest\nimport werkzeug.serving\nfrom markupsafe import Markup\nfrom werkzeug.exceptions import BadRequest\nfrom werkzeug.exceptions import Forbidden\nfrom werkzeug.exceptions import NotFound\nfrom werkzeug.http import parse_date\nfrom werkzeug.routing import BuildError\nfrom werkzeug.routing import RequestRedirect\n\nimport flask\nfrom flask.globals import app_ctx\nfrom flask.testing import FlaskClient\n\nrequire_cpython_gc = pytest.mark.skipif(\n python_implementation() != \"CPython\",\n reason=\"Requires CPython GC behavior\",\n)\n\n\ndef test_options_work(app, client):\n @app.route(\"/\", methods=[\"GET\", \"POST\"])\n def index():\n return \"Hello World\"\n\n rv = client.open(\"/\", method=\"OPTIONS\")\n assert sorted(rv.allow) == [\"GET\", \"HEAD\", \"OPTIONS\", \"POST\"]\n assert rv.data == b\"\"\n\n\ndef test_options_on_multiple_rules(app, client):\n @app.route(\"/\", methods=[\"GET\", \"POST\"])\n def index():\n return \"Hello World\"\n\n @app.route(\"/\", methods=[\"PUT\"])\n def index_put():\n return \"Aha!\"\n\n rv = client.open(\"/\", method=\"OPTIONS\")\n assert sorted(rv.allow) == [\"GET\", \"HEAD\", \"OPTIONS\", \"POST\", \"PUT\"]\n\n\n@pytest.mark.parametrize(\"method\", [\"get\", \"post\", \"put\", \"delete\", \"patch\"])\ndef test_method_route(app, client, method):\n method_route = getattr(app, method)\n client_method = getattr(client, method)\n\n @method_route(\"/\")\n def hello():\n return \"Hello\"\n\n assert client_method(\"/\").data == b\"Hello\"\n\n\ndef test_method_route_no_methods(app):\n with pytest.raises(TypeError):\n app.get(\"/\", methods=[\"GET\", \"POST\"])\n\n\ndef test_provide_automatic_options_attr_disable(\n app: flask.Flask, client: FlaskClient\n) -> None:\n \"\"\"Automatic options can be disabled by the view func attribute.\"\"\"\n\n def index():\n return \"Hello World!\"\n\n index.provide_automatic_options = False\n app.add_url_rule(\"/\", view_func=index)\n rv = client.options()\n assert rv.status_code == 405\n\n\ndef test_provide_automatic_options_attr_enable(\n app: flask.Flask, client: FlaskClient\n) -> None:\n \"\"\"When default automatic options is disabled in config, it can still be\n enabled by the view function attribute.\n \"\"\"\n app.config[\"PROVIDE_AUTOMATIC_OPTIONS\"] = False\n\n def index():\n return \"Hello World!\"\n\n index.provide_automatic_options = True\n app.add_url_rule(\"/\", view_func=index)\n rv = client.options()\n assert rv.allow == {\"GET\", \"HEAD\", \"OPTIONS\"}\n\n\ndef test_provide_automatic_options_arg_disable(\n app: flask.Flask, client: FlaskClient\n) -> None:\n \"\"\"Automatic options can be disabled by the route argument.\"\"\"\n\n @app.get(\"/\", provide_automatic_options=False)\n def index():\n return \"Hello World!\"\n\n rv = client.options()\n assert rv.status_code == 405\n\n\ndef test_provide_automatic_options_method_disable(\n app: flask.Flask, client: FlaskClient\n) -> None:\n \"\"\"Automatic options is ignored if the route handles options.\"\"\"\n\n @app.route(\"/\", methods=[\"OPTIONS\"])\n def index():\n return \"\", {\"X-Test\": \"test\"}\n\n rv = client.options()\n assert rv.headers[\"X-Test\"] == \"test\"\n\n\ndef test_request_dispatching(app, client):\n @app.route(\"/\")\n def index():\n return flask.request.method\n\n @app.route(\"/more\", methods=[\"GET\", \"POST\"])\n def more():\n return flask.request.method\n\n assert client.get(\"/\").data == b\"GET\"\n rv = client.post(\"/\")\n assert rv.status_code == 405\n assert sorted(rv.allow) == [\"GET\", \"HEAD\", \"OPTIONS\"]\n rv = client.head(\"/\")\n assert rv.status_code == 200\n assert not rv.data # head truncates\n assert client.post(\"/more\").data == b\"POST\"\n assert client.get(\"/more\").data == b\"GET\"\n rv = client.delete(\"/more\")\n assert rv.status_code == 405\n assert sorted(rv.allow) == [\"GET\", \"HEAD\", \"OPTIONS\", \"POST\"]\n\n\ndef test_disallow_string_for_allowed_methods(app):\n with pytest.raises(TypeError):\n app.add_url_rule(\"/\", methods=\"GET POST\", endpoint=\"test\")\n\n\ndef test_url_mapping(app, client):\n random_uuid4 = \"7eb41166-9ebf-4d26-b771-ea3f54f8b383\"\n\n def index():\n return flask.request.method\n\n def more():\n return flask.request.method\n\n def options():\n return random_uuid4\n\n app.add_url_rule(\"/\", \"index\", index)\n app.add_url_rule(\"/more\", \"more\", more, methods=[\"GET\", \"POST\"])\n\n # Issue 1288: Test that automatic options are not added\n # when non-uppercase 'options' in methods\n app.add_url_rule(\"/options\", \"options\", options, methods=[\"options\"])\n\n assert client.get(\"/\").data == b\"GET\"\n rv = client.post(\"/\")\n assert rv.status_code == 405\n assert sorted(rv.allow) == [\"GET\", \"HEAD\", \"OPTIONS\"]\n rv = client.head(\"/\")\n assert rv.status_code == 200\n assert not rv.data # head truncates\n assert client.post(\"/more\").data == b\"POST\"\n assert client.get(\"/more\").data == b\"GET\"\n rv = client.delete(\"/more\")\n assert rv.status_code == 405\n assert sorted(rv.allow) == [\"GET\", \"HEAD\", \"OPTIONS\", \"POST\"]\n rv = client.open(\"/options\", method=\"OPTIONS\")\n assert rv.status_code == 200\n assert random_uuid4 in rv.data.decode(\"utf-8\")\n\n\ndef test_werkzeug_routing(app, client):\n from werkzeug.routing import Rule\n from werkzeug.routing import Submount\n\n app.url_map.add(\n Submount(\"/foo\", [Rule(\"/bar\", endpoint=\"bar\"), Rule(\"/\", endpoint=\"index\")])\n )\n\n def bar():\n return \"bar\"\n\n def index():\n return \"index\"\n\n app.view_functions[\"bar\"] = bar\n app.view_functions[\"index\"] = index\n\n assert client.get(\"/foo/\").data == b\"index\"\n assert client.get(\"/foo/bar\").data == b\"bar\"\n\n\ndef test_endpoint_decorator(app, client):\n from werkzeug.routing import Rule\n from werkzeug.routing import Submount\n\n app.url_map.add(\n Submount(\"/foo\", [Rule(\"/bar\", endpoint=\"bar\"), Rule(\"/\", endpoint=\"index\")])\n )\n\n @app.endpoint(\"bar\")\n def bar():\n return \"bar\"\n\n @app.endpoint(\"index\")\n def index():\n return \"index\"\n\n assert client.get(\"/foo/\").data == b\"index\"\n assert client.get(\"/foo/bar\").data == b\"bar\"\n\n\ndef test_session_accessed(app: flask.Flask, client: FlaskClient) -> None:\n @app.post(\"/\")\n def do_set():\n flask.session[\"value\"] = flask.request.form[\"value\"]\n return \"value set\"\n\n @app.get(\"/\")\n def do_get():\n return flask.session.get(\"value\", \"None\")\n\n @app.get(\"/nothing\")\n def do_nothing() -> str:\n return \"\"\n\n with client:\n rv = client.get(\"/nothing\")\n assert \"cookie\" not in rv.vary\n assert not app_ctx._session.accessed\n assert not app_ctx._session.modified\n\n with client:\n rv = client.post(data={\"value\": \"42\"})\n assert rv.text == \"value set\"\n assert \"cookie\" in rv.vary\n assert app_ctx._session.accessed\n assert app_ctx._session.modified\n\n with client:\n rv = client.get()\n assert rv.text == \"42\"\n assert \"cookie\" in rv.vary\n assert app_ctx._session.accessed\n assert not app_ctx._session.modified\n\n with client:\n rv = client.get(\"/nothing\")\n assert rv.text == \"\"\n assert \"cookie\" not in rv.vary\n assert not app_ctx._session.accessed\n assert not app_ctx._session.modified\n\n\ndef test_session_path(app, client):\n app.config.update(APPLICATION_ROOT=\"/foo\")\n\n @app.route(\"/\")\n def index():\n flask.session[\"testing\"] = 42\n return \"Hello World\"\n\n rv = client.get(\"/\", \"http://example.com:8080/foo\")\n assert \"path=/foo\" in rv.headers[\"set-cookie\"].lower()\n\n\ndef test_session_using_application_root(app, client):\n class PrefixPathMiddleware:\n def __init__(self, app, prefix):\n self.app = app\n self.prefix = prefix\n\n def __call__(self, environ, start_response):\n environ[\"SCRIPT_NAME\"] = self.prefix\n return self.app(environ, start_response)\n\n app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, \"/bar\")\n app.config.update(APPLICATION_ROOT=\"/bar\")\n\n @app.route(\"/\")\n def index():\n flask.session[\"testing\"] = 42\n return \"Hello World\"\n\n rv = client.get(\"/\", \"http://example.com:8080/\")\n assert \"path=/bar\" in rv.headers[\"set-cookie\"].lower()\n\n\ndef test_session_using_session_settings(app, client):\n app.config.update(\n SERVER_NAME=\"www.example.com:8080\",\n APPLICATION_ROOT=\"/test\",\n SESSION_COOKIE_DOMAIN=\".example.com\",\n SESSION_COOKIE_HTTPONLY=False,\n SESSION_COOKIE_SECURE=True,\n SESSION_COOKIE_PARTITIONED=True,\n SESSION_COOKIE_SAMESITE=\"Lax\",\n SESSION_COOKIE_PATH=\"/\",\n )\n\n @app.route(\"/\")\n def index():\n flask.session[\"testing\"] = 42\n return \"Hello World\"\n\n @app.route(\"/clear\")\n def clear():\n flask.session.pop(\"testing\", None)\n return \"Goodbye World\"\n\n rv = client.get(\"/\", \"http://www.example.com:8080/test/\")\n cookie = rv.headers[\"set-cookie\"].lower()\n # or condition for Werkzeug < 2.3\n assert \"domain=example.com\" in cookie or \"domain=.example.com\" in cookie\n assert \"path=/\" in cookie\n assert \"secure\" in cookie\n assert \"httponly\" not in cookie\n assert \"samesite\" in cookie\n assert \"partitioned\" in cookie\n\n rv = client.get(\"/clear\", \"http://www.example.com:8080/test/\")\n cookie = rv.headers[\"set-cookie\"].lower()\n assert \"session=;\" in cookie\n # or condition for Werkzeug < 2.3\n assert \"domain=example.com\" in cookie or \"domain=.example.com\" in cookie\n assert \"path=/\" in cookie\n assert \"secure\" in cookie\n assert \"samesite\" in cookie\n assert \"partitioned\" in cookie\n\n\ndef test_session_using_samesite_attribute(app, client):\n @app.route(\"/\")\n def index():\n flask.session[\"testing\"] = 42\n return \"Hello World\"\n\n app.config.update(SESSION_COOKIE_SAMESITE=\"invalid\")\n\n with pytest.raises(ValueError):\n client.get(\"/\")\n\n app.config.update(SESSION_COOKIE_SAMESITE=None)\n rv = client.get(\"/\")\n cookie = rv.headers[\"set-cookie\"].lower()\n assert \"samesite\" not in cookie\n\n app.config.update(SESSION_COOKIE_SAMESITE=\"Strict\")\n rv = client.get(\"/\")\n cookie = rv.headers[\"set-cookie\"].lower()\n assert \"samesite=strict\" in cookie\n\n app.config.update(SESSION_COOKIE_SAMESITE=\"Lax\")\n rv = client.get(\"/\")\n cookie = rv.headers[\"set-cookie\"].lower()\n assert \"samesite=lax\" in cookie\n\n\ndef test_missing_session(app):\n app.secret_key = None\n\n def expect_exception(f, *args, **kwargs):\n e = pytest.raises(RuntimeError, f, *args, **kwargs)\n assert e.value.args and \"session is unavailable\" in e.value.args[0]\n\n with app.test_request_context():\n assert flask.session.get(\"missing_key\") is None\n expect_exception(flask.session.__setitem__, \"foo\", 42)\n expect_exception(flask.session.pop, \"foo\")\n\n\ndef test_session_secret_key_fallbacks(app, client) -> None:\n @app.post(\"/\")\n def set_session() -> str:\n flask.session[\"a\"] = 1\n return \"\"\n\n @app.get(\"/\")\n def get_session() -> dict[str, t.Any]:\n return dict(flask.session)\n\n # Set session with initial secret key, and two valid expiring keys\n app.secret_key, app.config[\"SECRET_KEY_FALLBACKS\"] = (\n \"0 key\",\n [\"-1 key\", \"-2 key\"],\n )\n client.post()\n assert client.get().json == {\"a\": 1}\n # Change secret key, session can't be loaded and appears empty\n app.secret_key = \"? key\"\n assert client.get().json == {}\n # Rotate the valid keys, session can be loaded\n app.secret_key, app.config[\"SECRET_KEY_FALLBACKS\"] = (\n \"+1 key\",\n [\"0 key\", \"-1 key\"],\n )\n assert client.get().json == {\"a\": 1}\n\n\ndef test_session_expiration(app, client):\n permanent = True\n\n @app.route(\"/\")\n def index():\n flask.session[\"test\"] = 42\n flask.session.permanent = permanent\n return \"\"\n\n @app.route(\"/test\")\n def test():\n return str(flask.session.permanent)\n\n rv = client.get(\"/\")\n assert \"set-cookie\" in rv.headers\n match = re.search(r\"(?i)\\bexpires=([^;]+)\", rv.headers[\"set-cookie\"])\n expires = parse_date(match.group())\n expected = datetime.now(timezone.utc) + app.permanent_session_lifetime\n assert expires.year == expected.year\n assert expires.month == expected.month\n assert expires.day == expected.day\n\n rv = client.get(\"/test\")\n assert rv.data == b\"True\"\n\n permanent = False\n rv = client.get(\"/\")\n assert \"set-cookie\" in rv.headers\n match = re.search(r\"\\bexpires=([^;]+)\", rv.headers[\"set-cookie\"])\n assert match is None\n\n\ndef test_session_stored_last(app, client):\n @app.after_request\n def modify_session(response):\n flask.session[\"foo\"] = 42\n return response\n\n @app.route(\"/\")\n def dump_session_contents():\n return repr(flask.session.get(\"foo\"))\n\n assert client.get(\"/\").data == b\"None\"\n assert client.get(\"/\").data == b\"42\"\n\n\ndef test_session_special_types(app, client):\n now = datetime.now(timezone.utc).replace(microsecond=0)\n the_uuid = uuid.uuid4()\n\n @app.route(\"/\")\n def dump_session_contents():\n flask.session[\"t\"] = (1, 2, 3)\n flask.session[\"b\"] = b\"\\xff\"\n flask.session[\"m\"] = Markup(\"\")\n flask.session[\"u\"] = the_uuid\n flask.session[\"d\"] = now\n flask.session[\"t_tag\"] = {\" t\": \"not-a-tuple\"}\n flask.session[\"di_t_tag\"] = {\" t__\": \"not-a-tuple\"}\n flask.session[\"di_tag\"] = {\" di\": \"not-a-dict\"}\n return \"\", 204\n\n with client:\n client.get(\"/\")\n s = flask.session\n assert s[\"t\"] == (1, 2, 3)\n assert type(s[\"b\"]) is bytes # noqa: E721\n assert s[\"b\"] == b\"\\xff\"\n assert type(s[\"m\"]) is Markup # noqa: E721\n assert s[\"m\"] == Markup(\"\")\n assert s[\"u\"] == the_uuid\n assert s[\"d\"] == now\n assert s[\"t_tag\"] == {\" t\": \"not-a-tuple\"}\n assert s[\"di_t_tag\"] == {\" t__\": \"not-a-tuple\"}\n assert s[\"di_tag\"] == {\" di\": \"not-a-dict\"}\n\n\ndef test_session_cookie_setting(app):\n is_permanent = True\n\n @app.route(\"/bump\")\n def bump():\n rv = flask.session[\"foo\"] = flask.session.get(\"foo\", 0) + 1\n flask.session.permanent = is_permanent\n return str(rv)\n\n @app.route(\"/read\")\n def read():\n return str(flask.session.get(\"foo\", 0))\n\n def run_test(expect_header):\n with app.test_client() as c:\n assert c.get(\"/bump\").data == b\"1\"\n assert c.get(\"/bump\").data == b\"2\"\n assert c.get(\"/bump\").data == b\"3\"\n\n rv = c.get(\"/read\")\n set_cookie = rv.headers.get(\"set-cookie\")\n assert (set_cookie is not None) == expect_header\n assert rv.data == b\"3\"\n\n is_permanent = True\n app.config[\"SESSION_REFRESH_EACH_REQUEST\"] = True\n run_test(expect_header=True)\n\n is_permanent = True\n app.config[\"SESSION_REFRESH_EACH_REQUEST\"] = False\n run_test(expect_header=False)\n\n is_permanent = False\n app.config[\"SESSION_REFRESH_EACH_REQUEST\"] = True\n run_test(expect_header=False)\n\n is_permanent = False\n app.config[\"SESSION_REFRESH_EACH_REQUEST\"] = False\n run_test(expect_header=False)\n\n\ndef test_session_vary_cookie(app, client):\n @app.route(\"/set\")\n def set_session():\n flask.session[\"test\"] = \"test\"\n return \"\"\n\n @app.route(\"/get\")\n def get():\n return flask.session.get(\"test\")\n\n @app.route(\"/getitem\")\n def getitem():\n return flask.session[\"test\"]\n\n @app.route(\"/setdefault\")\n def setdefault():\n return flask.session.setdefault(\"test\", \"default\")\n\n @app.route(\"/clear\")\n def clear():\n flask.session.clear()\n return \"\"\n\n @app.route(\"/vary-cookie-header-set\")\n def vary_cookie_header_set():\n response = flask.Response()\n response.vary.add(\"Cookie\")\n flask.session[\"test\"] = \"test\"\n return response\n\n @app.route(\"/vary-header-set\")\n def vary_header_set():\n response = flask.Response()\n response.vary.update((\"Accept-Encoding\", \"Accept-Language\"))\n flask.session[\"test\"] = \"test\"\n return response\n\n @app.route(\"/no-vary-header\")\n def no_vary_header():\n return \"\"\n\n def expect(path, header_value=\"Cookie\"):\n rv = client.get(path)\n\n if header_value:\n # The 'Vary' key should exist in the headers only once.\n assert len(rv.headers.get_all(\"Vary\")) == 1\n assert rv.headers[\"Vary\"] == header_value\n else:\n assert \"Vary\" not in rv.headers\n\n expect(\"/set\")\n expect(\"/get\")\n expect(\"/getitem\")\n expect(\"/setdefault\")\n expect(\"/clear\")\n expect(\"/vary-cookie-header-set\")\n expect(\"/vary-header-set\", \"Accept-Encoding, Accept-Language, Cookie\")\n expect(\"/no-vary-header\", None)\n\n\ndef test_session_refresh_vary(app, client):\n @app.get(\"/login\")\n def login():\n flask.session[\"user_id\"] = 1\n flask.session.permanent = True\n return \"\"\n\n @app.get(\"/ignored\")\n def ignored():\n return \"\"\n\n rv = client.get(\"/login\")\n assert rv.headers[\"Vary\"] == \"Cookie\"\n rv = client.get(\"/ignored\")\n assert rv.headers[\"Vary\"] == \"Cookie\"\n\n\ndef test_flashes(app, req_ctx):\n assert not flask.session.modified\n flask.flash(\"Zap\")\n flask.session.modified = False\n flask.flash(\"Zip\")\n assert flask.session.modified\n assert list(flask.get_flashed_messages()) == [\"Zap\", \"Zip\"]\n\n\ndef test_extended_flashing(app):\n # Be sure app.testing=True below, else tests can fail silently.\n #\n # Specifically, if app.testing is not set to True, the AssertionErrors\n # in the view functions will cause a 500 response to the test client\n # instead of propagating exceptions.\n\n @app.route(\"/\")\n def index():\n flask.flash(\"Hello World\")\n flask.flash(\"Hello World\", \"error\")\n flask.flash(Markup(\"Testing\"), \"warning\")\n return \"\"\n\n @app.route(\"/test/\")\n def test():\n messages = flask.get_flashed_messages()\n assert list(messages) == [\n \"Hello World\",\n \"Hello World\",\n Markup(\"Testing\"),\n ]\n return \"\"\n\n @app.route(\"/test_with_categories/\")\n def test_with_categories():\n messages = flask.get_flashed_messages(with_categories=True)\n assert len(messages) == 3\n assert list(messages) == [\n (\"message\", \"Hello World\"),\n (\"error\", \"Hello World\"),\n (\"warning\", Markup(\"Testing\")),\n ]\n return \"\"\n\n @app.route(\"/test_filter/\")\n def test_filter():\n messages = flask.get_flashed_messages(\n category_filter=[\"message\"], with_categories=True\n )\n assert list(messages) == [(\"message\", \"Hello World\")]\n return \"\"\n\n @app.route(\"/test_filters/\")\n def test_filters():\n messages = flask.get_flashed_messages(\n category_filter=[\"message\", \"warning\"], with_categories=True\n )\n assert list(messages) == [\n (\"message\", \"Hello World\"),\n (\"warning\", Markup(\"Testing\")),\n ]\n return \"\"\n\n @app.route(\"/test_filters_without_returning_categories/\")\n def test_filters2():\n messages = flask.get_flashed_messages(category_filter=[\"message\", \"warning\"])\n assert len(messages) == 2\n assert messages[0] == \"Hello World\"\n assert messages[1] == Markup(\"Testing\")\n return \"\"\n\n # Create new test client on each test to clean flashed messages.\n\n client = app.test_client()\n client.get(\"/\")\n client.get(\"/test_with_categories/\")\n\n client = app.test_client()\n client.get(\"/\")\n client.get(\"/test_filter/\")\n\n client = app.test_client()\n client.get(\"/\")\n client.get(\"/test_filters/\")\n\n client = app.test_client()\n client.get(\"/\")\n client.get(\"/test_filters_without_returning_categories/\")\n\n\ndef test_request_processing(app, client):\n evts = []\n\n @app.before_request\n def before_request():\n evts.append(\"before\")\n\n @app.after_request\n def after_request(response):\n response.data += b\"|after\"\n evts.append(\"after\")\n return response\n\n @app.route(\"/\")\n def index():\n assert \"before\" in evts\n assert \"after\" not in evts\n return \"request\"\n\n assert \"after\" not in evts\n rv = client.get(\"/\").data\n assert \"after\" in evts\n assert rv == b\"request|after\"\n\n\ndef test_request_preprocessing_early_return(app, client):\n evts = []\n\n @app.before_request\n def before_request1():\n evts.append(1)\n\n @app.before_request\n def before_request2():\n evts.append(2)\n return \"hello\"\n\n @app.before_request\n def before_request3():\n evts.append(3)\n return \"bye\"\n\n @app.route(\"/\")\n def index():\n evts.append(\"index\")\n return \"damnit\"\n\n rv = client.get(\"/\").data.strip()\n assert rv == b\"hello\"\n assert evts == [1, 2]\n\n\ndef test_after_request_processing(app, client):\n @app.route(\"/\")\n def index():\n @flask.after_this_request\n def foo(response):\n response.headers[\"X-Foo\"] = \"a header\"\n return response\n\n return \"Test\"\n\n resp = client.get(\"/\")\n assert resp.status_code == 200\n assert resp.headers[\"X-Foo\"] == \"a header\"\n\n\ndef test_teardown_request_handler(app, client):\n called = []\n\n @app.teardown_request\n def teardown_request(exc):\n called.append(True)\n return \"Ignored\"\n\n @app.route(\"/\")\n def root():\n return \"Response\"\n\n rv = client.get(\"/\")\n assert rv.status_code == 200\n assert b\"Response\" in rv.data\n assert len(called) == 1\n\n\ndef test_teardown_request_handler_debug_mode(app, client):\n called = []\n\n @app.teardown_request\n def teardown_request(exc):\n called.append(True)\n return \"Ignored\"\n\n @app.route(\"/\")\n def root():\n return \"Response\"\n\n rv = client.get(\"/\")\n assert rv.status_code == 200\n assert b\"Response\" in rv.data\n assert len(called) == 1\n\n\ndef test_teardown_request_handler_error(app, client):\n called = []\n app.testing = False\n\n @app.teardown_request\n def teardown_request1(exc):\n assert type(exc) is ZeroDivisionError\n called.append(True)\n # This raises a new error and blows away sys.exc_info(), so we can\n # test that all teardown_requests get passed the same original\n # exception.\n try:\n raise TypeError()\n except Exception:\n pass\n\n @app.teardown_request\n def teardown_request2(exc):\n assert type(exc) is ZeroDivisionError\n called.append(True)\n # This raises a new error and blows away sys.exc_info(), so we can\n # test that all teardown_requests get passed the same original\n # exception.\n try:\n raise TypeError()\n except Exception:\n pass\n\n @app.route(\"/\")\n def fails():\n raise ZeroDivisionError\n\n rv = client.get(\"/\")\n assert rv.status_code == 500\n assert b\"Internal Server Error\" in rv.data\n assert len(called) == 2\n\n\ndef test_before_after_request_order(app, client):\n called = []\n\n @app.before_request\n def before1():\n called.append(1)\n\n @app.before_request\n def before2():\n called.append(2)\n\n @app.after_request\n def after1(response):\n called.append(4)\n return response\n\n @app.after_request\n def after2(response):\n called.append(3)\n return response\n\n @app.teardown_request\n def finish1(exc):\n called.append(6)\n\n @app.teardown_request\n def finish2(exc):\n called.append(5)\n\n @app.route(\"/\")\n def index():\n return \"42\"\n\n rv = client.get(\"/\")\n assert rv.data == b\"42\"\n assert called == [1, 2, 3, 4, 5, 6]\n\n\ndef test_error_handling(app, client):\n app.testing = False\n\n @app.errorhandler(404)\n def not_found(e):\n return \"not found\", 404\n\n @app.errorhandler(500)\n def internal_server_error(e):\n return \"internal server error\", 500\n\n @app.errorhandler(Forbidden)\n def forbidden(e):\n return \"forbidden\", 403\n\n @app.route(\"/\")\n def index():\n flask.abort(404)\n\n @app.route(\"/error\")\n def error():\n raise ZeroDivisionError\n\n @app.route(\"/forbidden\")\n def error2():\n flask.abort(403)\n\n rv = client.get(\"/\")\n assert rv.status_code == 404\n assert rv.data == b\"not found\"\n rv = client.get(\"/error\")\n assert rv.status_code == 500\n assert b\"internal server error\" == rv.data\n rv = client.get(\"/forbidden\")\n assert rv.status_code == 403\n assert b\"forbidden\" == rv.data\n\n\ndef test_error_handling_processing(app, client):\n app.testing = False\n\n @app.errorhandler(500)\n def internal_server_error(e):\n return \"internal server error\", 500\n\n @app.route(\"/\")\n def broken_func():\n raise ZeroDivisionError\n\n @app.after_request\n def after_request(resp):\n resp.mimetype = \"text/x-special\"\n return resp\n\n resp = client.get(\"/\")\n assert resp.mimetype == \"text/x-special\"\n assert resp.data == b\"internal server error\"\n\n\ndef test_baseexception_error_handling(app, client):\n app.testing = False\n\n @app.route(\"/\")\n def broken_func():\n raise KeyboardInterrupt()\n\n with pytest.raises(KeyboardInterrupt):\n client.get(\"/\")\n\n\ndef test_before_request_and_routing_errors(app, client):\n @app.before_request\n def attach_something():\n flask.g.something = \"value\"\n\n @app.errorhandler(404)\n def return_something(error):\n return flask.g.something, 404\n\n rv = client.get(\"/\")\n assert rv.status_code == 404\n assert rv.data == b\"value\"\n\n\ndef test_user_error_handling(app, client):\n class MyException(Exception):\n pass\n\n @app.errorhandler(MyException)\n def handle_my_exception(e):\n assert isinstance(e, MyException)\n return \"42\"\n\n @app.route(\"/\")\n def index():\n raise MyException()\n\n assert client.get(\"/\").data == b\"42\"\n\n\ndef test_http_error_subclass_handling(app, client):\n class ForbiddenSubclass(Forbidden):\n pass\n\n @app.errorhandler(ForbiddenSubclass)\n def handle_forbidden_subclass(e):\n assert isinstance(e, ForbiddenSubclass)\n return \"banana\"\n\n @app.errorhandler(403)\n def handle_403(e):\n assert not isinstance(e, ForbiddenSubclass)\n assert isinstance(e, Forbidden)\n return \"apple\"\n\n @app.route(\"/1\")\n def index1():\n raise ForbiddenSubclass()\n\n @app.route(\"/2\")\n def index2():\n flask.abort(403)\n\n @app.route(\"/3\")\n def index3():\n raise Forbidden()\n\n assert client.get(\"/1\").data == b\"banana\"\n assert client.get(\"/2\").data == b\"apple\"\n assert client.get(\"/3\").data == b\"apple\"\n\n\ndef test_errorhandler_precedence(app, client):\n class E1(Exception):\n pass\n\n class E2(Exception):\n pass\n\n class E3(E1, E2):\n pass\n\n @app.errorhandler(E2)\n def handle_e2(e):\n return \"E2\"\n\n @app.errorhandler(Exception)\n def handle_exception(e):\n return \"Exception\"\n\n @app.route(\"/E1\")\n def raise_e1():\n raise E1\n\n @app.route(\"/E3\")\n def raise_e3():\n raise E3\n\n rv = client.get(\"/E1\")\n assert rv.data == b\"Exception\"\n\n rv = client.get(\"/E3\")\n assert rv.data == b\"E2\"\n\n\n@pytest.mark.parametrize(\n (\"debug\", \"trap\", \"expect_key\", \"expect_abort\"),\n [(False, None, True, True), (True, None, False, True), (False, True, False, False)],\n)\ndef test_trap_bad_request_key_error(app, client, debug, trap, expect_key, expect_abort):\n app.config[\"DEBUG\"] = debug\n app.config[\"TRAP_BAD_REQUEST_ERRORS\"] = trap\n\n @app.route(\"/key\")\n def fail():\n flask.request.form[\"missing_key\"]\n\n @app.route(\"/abort\")\n def allow_abort():\n flask.abort(400)\n\n if expect_key:\n rv = client.get(\"/key\")\n assert rv.status_code == 400\n assert b\"missing_key\" not in rv.data\n else:\n with pytest.raises(KeyError) as exc_info:\n client.get(\"/key\")\n\n assert exc_info.errisinstance(BadRequest)\n assert \"missing_key\" in exc_info.value.get_description()\n\n if expect_abort:\n rv = client.get(\"/abort\")\n assert rv.status_code == 400\n else:\n with pytest.raises(BadRequest):\n client.get(\"/abort\")\n\n\ndef test_trapping_of_all_http_exceptions(app, client):\n app.config[\"TRAP_HTTP_EXCEPTIONS\"] = True\n\n @app.route(\"/fail\")\n def fail():\n flask.abort(404)\n\n with pytest.raises(NotFound):\n client.get(\"/fail\")\n\n\ndef test_error_handler_after_processor_error(app, client):\n app.testing = False\n\n @app.before_request\n def before_request():\n if _trigger == \"before\":\n raise ZeroDivisionError\n\n @app.after_request\n def after_request(response):\n if _trigger == \"after\":\n raise ZeroDivisionError\n\n return response\n\n @app.route(\"/\")\n def index():\n return \"Foo\"\n\n @app.errorhandler(500)\n def internal_server_error(e):\n return \"Hello Server Error\", 500\n\n for _trigger in \"before\", \"after\":\n rv = client.get(\"/\")\n assert rv.status_code == 500\n assert rv.data == b\"Hello Server Error\"\n\n\ndef test_enctype_debug_helper(app, client):\n from flask.debughelpers import DebugFilesKeyError\n\n app.debug = True\n\n @app.route(\"/fail\", methods=[\"POST\"])\n def index():\n return flask.request.files[\"foo\"].filename\n\n with pytest.raises(DebugFilesKeyError) as e:\n client.post(\"/fail\", data={\"foo\": \"index.txt\"})\n assert \"no file contents were transmitted\" in str(e.value)\n assert \"This was submitted: 'index.txt'\" in str(e.value)\n\n\ndef test_response_types(app, client):\n @app.route(\"/text\")\n def from_text():\n return \"Hällo Wörld\"\n\n @app.route(\"/bytes\")\n def from_bytes():\n return \"Hällo Wörld\".encode()\n\n @app.route(\"/full_tuple\")\n def from_full_tuple():\n return (\n \"Meh\",\n 400,\n {\"X-Foo\": \"Testing\", \"Content-Type\": \"text/plain; charset=utf-8\"},\n )\n\n @app.route(\"/text_headers\")\n def from_text_headers():\n return \"Hello\", {\"X-Foo\": \"Test\", \"Content-Type\": \"text/plain; charset=utf-8\"}\n\n @app.route(\"/text_status\")\n def from_text_status():\n return \"Hi, status!\", 400\n\n @app.route(\"/response_headers\")\n def from_response_headers():\n return (\n flask.Response(\n \"Hello world\", 404, {\"Content-Type\": \"text/html\", \"X-Foo\": \"Baz\"}\n ),\n {\"Content-Type\": \"text/plain\", \"X-Foo\": \"Bar\", \"X-Bar\": \"Foo\"},\n )\n\n @app.route(\"/response_status\")\n def from_response_status():\n return app.response_class(\"Hello world\", 400), 500\n\n @app.route(\"/wsgi\")\n def from_wsgi():\n return NotFound()\n\n @app.route(\"/dict\")\n def from_dict():\n return {\"foo\": \"bar\"}, 201\n\n @app.route(\"/list\")\n def from_list():\n return [\"foo\", \"bar\"], 201\n\n assert client.get(\"/text\").data == \"Hällo Wörld\".encode()\n assert client.get(\"/bytes\").data == \"Hällo Wörld\".encode()\n\n rv = client.get(\"/full_tuple\")\n assert rv.data == b\"Meh\"\n assert rv.headers[\"X-Foo\"] == \"Testing\"\n assert rv.status_code == 400\n assert rv.mimetype == \"text/plain\"\n\n rv = client.get(\"/text_headers\")\n assert rv.data == b\"Hello\"\n assert rv.headers[\"X-Foo\"] == \"Test\"\n assert rv.status_code == 200\n assert rv.mimetype == \"text/plain\"\n\n rv = client.get(\"/text_status\")\n assert rv.data == b\"Hi, status!\"\n assert rv.status_code == 400\n assert rv.mimetype == \"text/html\"\n\n rv = client.get(\"/response_headers\")\n assert rv.data == b\"Hello world\"\n assert rv.content_type == \"text/plain\"\n assert rv.headers.getlist(\"X-Foo\") == [\"Bar\"]\n assert rv.headers[\"X-Bar\"] == \"Foo\"\n assert rv.status_code == 404\n\n rv = client.get(\"/response_status\")\n assert rv.data == b\"Hello world\"\n assert rv.status_code == 500\n\n rv = client.get(\"/wsgi\")\n assert b\"Not Found\" in rv.data\n assert rv.status_code == 404\n\n rv = client.get(\"/dict\")\n assert rv.json == {\"foo\": \"bar\"}\n assert rv.status_code == 201\n\n rv = client.get(\"/list\")\n assert rv.json == [\"foo\", \"bar\"]\n assert rv.status_code == 201\n\n\ndef test_response_type_errors():\n app = flask.Flask(__name__)\n app.testing = True\n\n @app.route(\"/none\")\n def from_none():\n pass\n\n @app.route(\"/small_tuple\")\n def from_small_tuple():\n return (\"Hello\",)\n\n @app.route(\"/large_tuple\")\n def from_large_tuple():\n return \"Hello\", 234, {\"X-Foo\": \"Bar\"}, \"???\"\n\n @app.route(\"/bad_type\")\n def from_bad_type():\n return True\n\n @app.route(\"/bad_wsgi\")\n def from_bad_wsgi():\n return lambda: None\n\n c = app.test_client()\n\n with pytest.raises(TypeError) as e:\n c.get(\"/none\")\n\n assert \"returned None\" in str(e.value)\n assert \"from_none\" in str(e.value)\n\n with pytest.raises(TypeError) as e:\n c.get(\"/small_tuple\")\n\n assert \"tuple must have the form\" in str(e.value)\n\n with pytest.raises(TypeError):\n c.get(\"/large_tuple\")\n\n with pytest.raises(TypeError) as e:\n c.get(\"/bad_type\")\n\n assert \"it was a bool\" in str(e.value)\n\n with pytest.raises(TypeError):\n c.get(\"/bad_wsgi\")\n\n\ndef test_make_response(app, req_ctx):\n rv = flask.make_response()\n assert rv.status_code == 200\n assert rv.data == b\"\"\n assert rv.mimetype == \"text/html\"\n\n rv = flask.make_response(\"Awesome\")\n assert rv.status_code == 200\n assert rv.data == b\"Awesome\"\n assert rv.mimetype == \"text/html\"\n\n rv = flask.make_response(\"W00t\", 404)\n assert rv.status_code == 404\n assert rv.data == b\"W00t\"\n assert rv.mimetype == \"text/html\"\n\n rv = flask.make_response(c for c in \"Hello\")\n assert rv.status_code == 200\n assert rv.data == b\"Hello\"\n assert rv.mimetype == \"text/html\"\n\n\ndef test_make_response_with_response_instance(app, req_ctx):\n rv = flask.make_response(flask.jsonify({\"msg\": \"W00t\"}), 400)\n assert rv.status_code == 400\n assert rv.data == b'{\"msg\":\"W00t\"}\\n'\n assert rv.mimetype == \"application/json\"\n\n rv = flask.make_response(flask.Response(\"\"), 400)\n assert rv.status_code == 400\n assert rv.data == b\"\"\n assert rv.mimetype == \"text/html\"\n\n rv = flask.make_response(\n flask.Response(\"\", headers={\"Content-Type\": \"text/html\"}),\n 400,\n [(\"X-Foo\", \"bar\")],\n )\n assert rv.status_code == 400\n assert rv.headers[\"Content-Type\"] == \"text/html\"\n assert rv.headers[\"X-Foo\"] == \"bar\"\n\n\n@pytest.mark.parametrize(\"compact\", [True, False])\ndef test_jsonify_no_prettyprint(app, compact):\n app.json.compact = compact\n rv = app.json.response({\"msg\": {\"submsg\": \"W00t\"}, \"msg2\": \"foobar\"})\n data = rv.data.strip()\n assert (b\" \" not in data) is compact\n assert (b\"\\n\" not in data) is compact\n\n\ndef test_jsonify_mimetype(app, req_ctx):\n app.json.mimetype = \"application/vnd.api+json\"\n msg = {\"msg\": {\"submsg\": \"W00t\"}}\n rv = flask.make_response(flask.jsonify(msg), 200)\n assert rv.mimetype == \"application/vnd.api+json\"\n\n\ndef test_json_dump_dataclass(app, req_ctx):\n from dataclasses import make_dataclass\n\n Data = make_dataclass(\"Data\", [(\"name\", str)])\n value = app.json.dumps(Data(\"Flask\"))\n value = app.json.loads(value)\n assert value == {\"name\": \"Flask\"}\n\n\ndef test_jsonify_args_and_kwargs_check(app, req_ctx):\n with pytest.raises(TypeError) as e:\n flask.jsonify(\"fake args\", kwargs=\"fake\")\n assert \"args or kwargs\" in str(e.value)\n\n\ndef test_url_generation(app, req_ctx):\n @app.route(\"/hello/\", methods=[\"POST\"])\n def hello():\n pass\n\n assert flask.url_for(\"hello\", name=\"test x\") == \"/hello/test%20x\"\n assert (\n flask.url_for(\"hello\", name=\"test x\", _external=True)\n == \"http://localhost/hello/test%20x\"\n )\n\n\ndef test_build_error_handler(app):\n # Test base case, a URL which results in a BuildError.\n with app.test_request_context():\n pytest.raises(BuildError, flask.url_for, \"spam\")\n\n # Verify the error is re-raised if not the current exception.\n try:\n with app.test_request_context():\n flask.url_for(\"spam\")\n except BuildError as err:\n error = err\n try:\n raise RuntimeError(\"Test case where BuildError is not current.\")\n except RuntimeError:\n pytest.raises(BuildError, app.handle_url_build_error, error, \"spam\", {})\n\n # Test a custom handler.\n def handler(error, endpoint, values):\n # Just a test.\n return \"/test_handler/\"\n\n app.url_build_error_handlers.append(handler)\n with app.test_request_context():\n assert flask.url_for(\"spam\") == \"/test_handler/\"\n\n\ndef test_build_error_handler_reraise(app):\n # Test a custom handler which reraises the BuildError\n def handler_raises_build_error(error, endpoint, values):\n raise error\n\n app.url_build_error_handlers.append(handler_raises_build_error)\n\n with app.test_request_context():\n pytest.raises(BuildError, flask.url_for, \"not.existing\")\n\n\ndef test_url_for_passes_special_values_to_build_error_handler(app):\n @app.url_build_error_handlers.append\n def handler(error, endpoint, values):\n assert values == {\n \"_external\": False,\n \"_anchor\": None,\n \"_method\": None,\n \"_scheme\": None,\n }\n return \"handled\"\n\n with app.test_request_context():\n flask.url_for(\"/\")\n\n\ndef test_static_files(app, client):\n with client.get(\"/static/index.html\") as rv:\n assert rv.status_code == 200\n assert rv.data.strip() == b\"

Hello World!

\"\n with app.test_request_context():\n assert (\n flask.url_for(\"static\", filename=\"index.html\") == \"/static/index.html\"\n )\n\n\ndef test_static_url_path():\n app = flask.Flask(__name__, static_url_path=\"/foo\")\n app.testing = True\n\n with app.test_client().get(\"/foo/index.html\") as rv:\n assert rv.status_code == 200\n\n with app.test_request_context():\n assert flask.url_for(\"static\", filename=\"index.html\") == \"/foo/index.html\"\n\n\ndef test_static_url_path_with_ending_slash():\n app = flask.Flask(__name__, static_url_path=\"/foo/\")\n app.testing = True\n\n with app.test_client().get(\"/foo/index.html\") as rv:\n assert rv.status_code == 200\n\n with app.test_request_context():\n assert flask.url_for(\"static\", filename=\"index.html\") == \"/foo/index.html\"\n\n\ndef test_static_url_empty_path(app):\n app = flask.Flask(__name__, static_folder=\"\", static_url_path=\"\")\n\n with app.test_client().open(\"/static/index.html\", method=\"GET\") as rv:\n assert rv.status_code == 200\n\n\ndef test_static_url_empty_path_default(app):\n app = flask.Flask(__name__, static_folder=\"\")\n\n with app.test_client().open(\"/static/index.html\", method=\"GET\") as rv:\n assert rv.status_code == 200\n\n\ndef test_static_folder_with_pathlib_path(app):\n from pathlib import Path\n\n app = flask.Flask(__name__, static_folder=Path(\"static\"))\n\n with app.test_client().open(\"/static/index.html\", method=\"GET\") as rv:\n assert rv.status_code == 200\n\n\ndef test_static_folder_with_ending_slash():\n app = flask.Flask(__name__, static_folder=\"static/\")\n\n @app.route(\"/\")\n def catch_all(path):\n return path\n\n rv = app.test_client().get(\"/catch/all\")\n assert rv.data == b\"catch/all\"\n\n\ndef test_static_route_with_host_matching():\n app = flask.Flask(__name__, host_matching=True, static_host=\"example.com\")\n c = app.test_client()\n\n with c.get(\"http://example.com/static/index.html\") as rv:\n assert rv.status_code == 200\n\n with app.test_request_context():\n rv = flask.url_for(\"static\", filename=\"index.html\", _external=True)\n assert rv == \"http://example.com/static/index.html\"\n # Providing static_host without host_matching=True should error.\n with pytest.raises(AssertionError):\n flask.Flask(__name__, static_host=\"example.com\")\n # Providing host_matching=True with static_folder\n # but without static_host should error.\n with pytest.raises(AssertionError):\n flask.Flask(__name__, host_matching=True)\n # Providing host_matching=True without static_host\n # but with static_folder=None should not error.\n flask.Flask(__name__, host_matching=True, static_folder=None)\n\n\ndef test_request_locals():\n assert repr(flask.g) == \"\"\n assert not flask.g\n\n\nwerkzeug_3_2 = importlib.metadata.version(\"werkzeug\") >= \"3.2.\"\n\n\n@pytest.mark.parametrize(\n (\"subdomain_matching\", \"host_matching\", \"expect_subdomain\", \"expect_host\"),\n [\n (False, False, \"default\", \"default\"),\n (True, False, \"abc\", \"\"),\n (False, True, \"abc\", \"default\"),\n ],\n)\ndef test_server_name_matching(\n subdomain_matching: bool,\n host_matching: bool,\n expect_subdomain: str,\n expect_host: str,\n) -> None:\n app = flask.Flask(\n __name__,\n subdomain_matching=subdomain_matching,\n host_matching=host_matching,\n static_host=\"example.test\" if host_matching else None,\n )\n app.config[\"SERVER_NAME\"] = \"example.test\"\n\n @app.route(\"/\", defaults={\"name\": \"default\"}, host=\"\")\n @app.route(\"/\", subdomain=\"\", host=\".example.test\")\n def index(name: str) -> str:\n return name\n\n client = app.test_client()\n\n r = client.get(base_url=\"http://example.test\")\n assert r.text == \"default\"\n\n r = client.get(base_url=\"http://abc.example.test\")\n assert r.text == expect_subdomain\n\n with pytest.warns() if subdomain_matching else nullcontext():\n r = client.get(base_url=\"http://xyz.other.test\")\n\n if werkzeug_3_2:\n assert r.text == \"default\"\n else:\n assert r.text == expect_host\n\n\ndef test_server_name_subdomain():\n app = flask.Flask(__name__, subdomain_matching=True)\n client = app.test_client()\n\n @app.route(\"/\")\n def index():\n return \"default\"\n\n @app.route(\"/\", subdomain=\"foo\")\n def subdomain():\n return \"subdomain\"\n\n app.config[\"SERVER_NAME\"] = \"dev.local:5000\"\n rv = client.get(\"/\")\n assert rv.data == b\"default\"\n\n rv = client.get(\"/\", \"http://dev.local:5000\")\n assert rv.data == b\"default\"\n\n rv = client.get(\"/\", \"https://dev.local:5000\")\n assert rv.data == b\"default\"\n\n app.config[\"SERVER_NAME\"] = \"dev.local:443\"\n rv = client.get(\"/\", \"https://dev.local\")\n\n # Werkzeug 1.0 fixes matching https scheme with 443 port\n if rv.status_code != 404:\n assert rv.data == b\"default\"\n\n app.config[\"SERVER_NAME\"] = \"dev.local\"\n rv = client.get(\"/\", \"https://dev.local\")\n assert rv.data == b\"default\"\n\n with pytest.warns(match=\"Current server name\"):\n rv = client.get(\"/\", \"http://foo.localhost\")\n\n if werkzeug_3_2:\n assert rv.status_code == 200\n else:\n assert rv.status_code == 404\n\n rv = client.get(\"/\", \"http://foo.dev.local\")\n assert rv.data == b\"subdomain\"\n\n\n@pytest.mark.parametrize(\"key\", [\"TESTING\", \"PROPAGATE_EXCEPTIONS\", \"DEBUG\", None])\ndef test_exception_propagation(app, client, key):\n app.testing = False\n\n @app.route(\"/\")\n def index():\n raise ZeroDivisionError\n\n if key is not None:\n app.config[key] = True\n\n with pytest.raises(ZeroDivisionError):\n client.get(\"/\")\n else:\n assert client.get(\"/\").status_code == 500\n\n\n@pytest.mark.parametrize(\"debug\", [True, False])\n@pytest.mark.parametrize(\"use_debugger\", [True, False])\n@pytest.mark.parametrize(\"use_reloader\", [True, False])\n@pytest.mark.parametrize(\"propagate_exceptions\", [None, True, False])\ndef test_werkzeug_passthrough_errors(\n monkeypatch, debug, use_debugger, use_reloader, propagate_exceptions, app\n):\n rv = {}\n\n # Mocks werkzeug.serving.run_simple method\n def run_simple_mock(*args, **kwargs):\n rv[\"passthrough_errors\"] = kwargs.get(\"passthrough_errors\")\n\n monkeypatch.setattr(werkzeug.serving, \"run_simple\", run_simple_mock)\n app.config[\"PROPAGATE_EXCEPTIONS\"] = propagate_exceptions\n app.run(debug=debug, use_debugger=use_debugger, use_reloader=use_reloader)\n\n\ndef test_url_processors(app, client):\n @app.url_defaults\n def add_language_code(endpoint, values):\n if flask.g.lang_code is not None and app.url_map.is_endpoint_expecting(\n endpoint, \"lang_code\"\n ):\n values.setdefault(\"lang_code\", flask.g.lang_code)\n\n @app.url_value_preprocessor\n def pull_lang_code(endpoint, values):\n flask.g.lang_code = values.pop(\"lang_code\", None)\n\n @app.route(\"//\")\n def index():\n return flask.url_for(\"about\")\n\n @app.route(\"//about\")\n def about():\n return flask.url_for(\"something_else\")\n\n @app.route(\"/foo\")\n def something_else():\n return flask.url_for(\"about\", lang_code=\"en\")\n\n assert client.get(\"/de/\").data == b\"/de/about\"\n assert client.get(\"/de/about\").data == b\"/foo\"\n assert client.get(\"/foo\").data == b\"/en/about\"\n\n\ndef test_inject_blueprint_url_defaults(app):\n bp = flask.Blueprint(\"foo\", __name__, template_folder=\"template\")\n\n @bp.url_defaults\n def bp_defaults(endpoint, values):\n values[\"page\"] = \"login\"\n\n @bp.route(\"/\")\n def view(page):\n pass\n\n app.register_blueprint(bp)\n\n values = dict()\n app.inject_url_defaults(\"foo.view\", values)\n expected = dict(page=\"login\")\n assert values == expected\n\n with app.test_request_context(\"/somepage\"):\n url = flask.url_for(\"foo.view\")\n expected = \"/login\"\n assert url == expected\n\n\ndef test_nonascii_pathinfo(app, client):\n @app.route(\"/киртест\")\n def index():\n return \"Hello World!\"\n\n rv = client.get(\"/киртест\")\n assert rv.data == b\"Hello World!\"\n\n\ndef test_no_setup_after_first_request(app, client):\n app.debug = True\n\n @app.route(\"/\")\n def index():\n return \"Awesome\"\n\n assert client.get(\"/\").data == b\"Awesome\"\n\n with pytest.raises(AssertionError) as exc_info:\n app.add_url_rule(\"/foo\", endpoint=\"late\")\n\n assert \"setup method 'add_url_rule'\" in str(exc_info.value)\n\n\ndef test_routing_redirect_debugging(monkeypatch, app, client):\n app.config[\"DEBUG\"] = True\n\n @app.route(\"/user/\", methods=[\"GET\", \"POST\"])\n def user():\n return flask.request.form[\"status\"]\n\n # default redirect code preserves form data\n rv = client.post(\"/user\", data={\"status\": \"success\"}, follow_redirects=True)\n assert rv.data == b\"success\"\n\n # 301 and 302 raise error\n monkeypatch.setattr(RequestRedirect, \"code\", 301)\n\n with client, pytest.raises(AssertionError) as exc_info:\n client.post(\"/user\", data={\"status\": \"error\"}, follow_redirects=True)\n\n assert \"canonical URL 'http://localhost/user/'\" in str(exc_info.value)\n\n\ndef test_route_decorator_custom_endpoint(app, client):\n app.debug = True\n\n @app.route(\"/foo/\")\n def foo():\n return flask.request.endpoint\n\n @app.route(\"/bar/\", endpoint=\"bar\")\n def for_bar():\n return flask.request.endpoint\n\n @app.route(\"/bar/123\", endpoint=\"123\")\n def for_bar_foo():\n return flask.request.endpoint\n\n with app.test_request_context():\n assert flask.url_for(\"foo\") == \"/foo/\"\n assert flask.url_for(\"bar\") == \"/bar/\"\n assert flask.url_for(\"123\") == \"/bar/123\"\n\n assert client.get(\"/foo/\").data == b\"foo\"\n assert client.get(\"/bar/\").data == b\"bar\"\n assert client.get(\"/bar/123\").data == b\"123\"\n\n\ndef test_get_method_on_g(app_ctx):\n assert flask.g.get(\"x\") is None\n assert flask.g.get(\"x\", 11) == 11\n flask.g.x = 42\n assert flask.g.get(\"x\") == 42\n assert flask.g.x == 42\n\n\ndef test_g_iteration_protocol(app_ctx):\n flask.g.foo = 23\n flask.g.bar = 42\n assert \"foo\" in flask.g\n assert \"foos\" not in flask.g\n assert sorted(flask.g) == [\"bar\", \"foo\"]\n\n\ndef test_subdomain_basic_support():\n app = flask.Flask(__name__, subdomain_matching=True)\n app.config[\"SERVER_NAME\"] = \"localhost.localdomain\"\n client = app.test_client()\n\n @app.route(\"/\")\n def normal_index():\n return \"normal index\"\n\n @app.route(\"/\", subdomain=\"test\")\n def test_index():\n return \"test index\"\n\n rv = client.get(\"/\", \"http://localhost.localdomain/\")\n assert rv.data == b\"normal index\"\n\n rv = client.get(\"/\", \"http://test.localhost.localdomain/\")\n assert rv.data == b\"test index\"\n\n\ndef test_subdomain_matching():\n app = flask.Flask(__name__, subdomain_matching=True)\n client = app.test_client()\n app.config[\"SERVER_NAME\"] = \"localhost.localdomain\"\n\n @app.route(\"/\", subdomain=\"\")\n def index(user):\n return f\"index for {user}\"\n\n rv = client.get(\"/\", \"http://mitsuhiko.localhost.localdomain/\")\n assert rv.data == b\"index for mitsuhiko\"\n\n\ndef test_subdomain_matching_with_ports():\n app = flask.Flask(__name__, subdomain_matching=True)\n app.config[\"SERVER_NAME\"] = \"localhost.localdomain:3000\"\n client = app.test_client()\n\n @app.route(\"/\", subdomain=\"\")\n def index(user):\n return f\"index for {user}\"\n\n rv = client.get(\"/\", \"http://mitsuhiko.localhost.localdomain:3000/\")\n assert rv.data == b\"index for mitsuhiko\"\n\n\n@pytest.mark.parametrize(\"matching\", (False, True))\ndef test_subdomain_matching_other_name(matching):\n app = flask.Flask(__name__, subdomain_matching=matching)\n app.config[\"SERVER_NAME\"] = \"localhost.localdomain:3000\"\n client = app.test_client()\n\n @app.route(\"/\")\n def index():\n return \"\", 204\n\n with pytest.warns(match=\"Current server name\") if matching else nullcontext():\n # ip address can't match name, but will fall back to default\n rv = client.get(\"/\", \"http://127.0.0.1:3000/\")\n\n if werkzeug_3_2:\n assert rv.status_code == 204\n else:\n assert rv.status_code == 404 if matching else 204\n\n # allow all subdomains if matching is disabled\n rv = client.get(\"/\", \"http://www.localhost.localdomain:3000/\")\n assert rv.status_code == 404 if matching else 204\n\n\ndef test_multi_route_rules(app, client):\n @app.route(\"/\")\n @app.route(\"//\")\n def index(test=\"a\"):\n return test\n\n rv = client.open(\"/\")\n assert rv.data == b\"a\"\n rv = client.open(\"/b/\")\n assert rv.data == b\"b\"\n\n\ndef test_multi_route_class_views(app, client):\n class View:\n def __init__(self, app):\n app.add_url_rule(\"/\", \"index\", self.index)\n app.add_url_rule(\"//\", \"index\", self.index)\n\n def index(self, test=\"a\"):\n return test\n\n _ = View(app)\n rv = client.open(\"/\")\n assert rv.data == b\"a\"\n rv = client.open(\"/b/\")\n assert rv.data == b\"b\"\n\n\ndef test_run_defaults(monkeypatch, app):\n rv = {}\n\n # Mocks werkzeug.serving.run_simple method\n def run_simple_mock(*args, **kwargs):\n rv[\"result\"] = \"running...\"\n\n monkeypatch.setattr(werkzeug.serving, \"run_simple\", run_simple_mock)\n app.run()\n assert rv[\"result\"] == \"running...\"\n\n\ndef test_run_server_port(monkeypatch, app):\n rv = {}\n\n # Mocks werkzeug.serving.run_simple method\n def run_simple_mock(hostname, port, application, *args, **kwargs):\n rv[\"result\"] = f\"running on {hostname}:{port} ...\"\n\n monkeypatch.setattr(werkzeug.serving, \"run_simple\", run_simple_mock)\n hostname, port = \"localhost\", 8000\n app.run(hostname, port, debug=True)\n assert rv[\"result\"] == f\"running on {hostname}:{port} ...\"\n\n\n@pytest.mark.parametrize(\n \"host,port,server_name,expect_host,expect_port\",\n (\n (None, None, \"pocoo.org:8080\", \"pocoo.org\", 8080),\n (\"localhost\", None, \"pocoo.org:8080\", \"localhost\", 8080),\n (None, 80, \"pocoo.org:8080\", \"pocoo.org\", 80),\n (\"localhost\", 80, \"pocoo.org:8080\", \"localhost\", 80),\n (\"localhost\", 0, \"localhost:8080\", \"localhost\", 0),\n (None, None, \"localhost:8080\", \"localhost\", 8080),\n (None, None, \"localhost:0\", \"localhost\", 0),\n ),\n)\ndef test_run_from_config(\n monkeypatch, host, port, server_name, expect_host, expect_port, app\n):\n def run_simple_mock(hostname, port, *args, **kwargs):\n assert hostname == expect_host\n assert port == expect_port\n\n monkeypatch.setattr(werkzeug.serving, \"run_simple\", run_simple_mock)\n app.config[\"SERVER_NAME\"] = server_name\n app.run(host, port)\n\n\ndef test_max_cookie_size(app, client, recwarn):\n app.config[\"MAX_COOKIE_SIZE\"] = 100\n\n # outside app context, default to Werkzeug static value,\n # which is also the default config\n response = flask.Response()\n default = flask.Flask.default_config[\"MAX_COOKIE_SIZE\"]\n assert response.max_cookie_size == default\n\n # inside app context, use app config\n with app.app_context():\n assert flask.Response().max_cookie_size == 100\n\n @app.route(\"/\")\n def index():\n r = flask.Response(\"\", status=204)\n r.set_cookie(\"foo\", \"bar\" * 100)\n return r\n\n client.get(\"/\")\n assert len(recwarn) == 1\n w = recwarn.pop()\n assert \"cookie is too large\" in str(w.message)\n\n app.config[\"MAX_COOKIE_SIZE\"] = 0\n\n client.get(\"/\")\n assert len(recwarn) == 0\n\n\n@require_cpython_gc\ndef test_app_freed_on_zero_refcount():\n # A Flask instance should not create a reference cycle that prevents CPython\n # from freeing it when all external references to it are released (see #3761).\n gc.disable()\n try:\n app = flask.Flask(__name__)\n assert app.view_functions[\"static\"]\n weak = weakref.ref(app)\n assert weak() is not None\n del app\n assert weak() is None\n finally:\n gc.enable()", "messages": null, "tools": null} {"id": "9387657a11780020", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/js-sourcemap/dep-optimized-malicious/index.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 309, "sha256": "a8240dade23be3bda75a6a52b4eb9b7ca6477b8a62e7905da054972cb208c3f6", "text": "const optimizedMalicious = 'value'\nmodule.exports = { optimizedMalicious }\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uLy4uL3BsYXlncm91bmQvanMtc291cmNlbWFwL3ZpdGUuY29uZmlnLmpzIl0sInNvdXJjZXNDb250ZW50IjpbbnVsbF0sIm1hcHBpbmdzIjoiQUFBQSIsIm5hbWVzIjpbXX0=", "messages": null, "tools": null} {"id": "939c0b935a7baafd", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/api/basic_json/swap.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 5529, "sha256": "f7b265568d175af3241bbc11c8e3fb10622d563b053701a37c41d97f5888cfd5", "text": "# nlohmann::basic_json::swap\n\n```cpp\n// (1)\nvoid swap(reference other) noexcept (\n std::is_nothrow_move_constructible::value &&\n std::is_nothrow_move_assignable::value &&\n std::is_nothrow_move_constructible::value &&\n std::is_nothrow_move_assignable::value\n);\n\n// (2)\nfriend void swap(reference left, reference right) noexcept (\n std::is_nothrow_move_constructible::value &&\n std::is_nothrow_move_assignable::value &&\n std::is_nothrow_move_constructible::value &&\n std::is_nothrow_move_assignable::value\n);\n\n// (3)\nvoid swap(array_t& other);\n\n// (4)\nvoid swap(object_t& other);\n\n// (5)\nvoid swap(string_t& other);\n\n// (6)\nvoid swap(binary_t& other);\n\n// (7)\nvoid swap(typename binary_t::container_type& other);\n```\n\n1. Exchanges the contents of the JSON value with those of `other`. Does not invoke any move, copy, or swap operations on\n individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. \n2. Exchanges the contents of the JSON value from `left` with those of `right`. Does not invoke any move, copy, or swap\n operations on individual elements. All iterators and references remain valid. The past-the-end iterator is\n invalidated. Implemented as a friend function callable via ADL.\n3. Exchanges the contents of a JSON array with those of `other`. Does not invoke any move, copy, or swap operations on\n individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. \n4. Exchanges the contents of a JSON object with those of `other`. Does not invoke any move, copy, or swap operations on\n individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.\n5. Exchanges the contents of a JSON string with those of `other`. Does not invoke any move, copy, or swap operations on\n individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.\n6. Exchanges the contents of a binary value with those of `other`. Does not invoke any move, copy, or swap operations on\n individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated.\n7. Exchanges the contents of a binary value with those of `other`. Does not invoke any move, copy, or swap operations on\n individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. Unlike\n version (6), no binary subtype is involved.\n\n## Parameters\n\n`other` (in, out)\n: value to exchange the contents with\n\n`left` (in, out)\n: value to exchange the contents with\n\n`right` (in, out)\n: value to exchange the contents with\n\n## Exceptions\n\n1. No-throw guarantee: this function never throws exceptions.\n2. No-throw guarantee: this function never throws exceptions.\n3. Throws [`type_error.310`](../../home/exceptions.md#jsonexceptiontype_error310) if called on JSON values other than\n arrays; example: `\"cannot use swap(array_t&) with boolean\"`\n4. Throws [`type_error.310`](../../home/exceptions.md#jsonexceptiontype_error310) if called on JSON values other than\n objects; example: `\"cannot use swap(object_t&) with boolean\"`\n5. Throws [`type_error.310`](../../home/exceptions.md#jsonexceptiontype_error310) if called on JSON values other than\n strings; example: `\"cannot use swap(string_t&) with boolean\"`\n6. Throws [`type_error.310`](../../home/exceptions.md#jsonexceptiontype_error310) if called on JSON values other than\n binaries; example: `\"cannot use swap(binary_t&) with boolean\"`\n7. Throws [`type_error.310`](../../home/exceptions.md#jsonexceptiontype_error310) if called on JSON values other than\n binaries; example: `\"cannot use swap(binary_t::container_type&) with boolean\"`\n\n## Complexity\n\nConstant.\n\n## Examples\n\n??? example \"Example: Swap JSON value (1, 2)\"\n\n The example below shows how JSON values can be swapped with `swap()`.\n \n ```cpp\n --8<-- \"examples/swap__reference.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/swap__reference.output\"\n ```\n\n??? example \"Example: Swap array (3)\"\n\n The example below shows how arrays can be swapped with `swap()`.\n \n ```cpp\n --8<-- \"examples/swap__array_t.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/swap__array_t.output\"\n ```\n\n??? example \"Example: Swap object (4)\"\n\n The example below shows how objects can be swapped with `swap()`.\n \n ```cpp\n --8<-- \"examples/swap__object_t.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/swap__object_t.output\"\n ```\n\n??? example \"Example: Swap string (5)\"\n\n The example below shows how strings can be swapped with `swap()`.\n \n ```cpp\n --8<-- \"examples/swap__string_t.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/swap__string_t.output\"\n ```\n\n??? example \"Example: Swap binary (6)\"\n\n The example below shows how binary values can be swapped with `swap()`.\n \n ```cpp\n --8<-- \"examples/swap__binary_t.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/swap__binary_t.output\"\n ```\n\n## See also\n\n- [std::swap](std_swap.md)\n- [operator=](operator=.md) copy assignment\n- [basic_json](basic_json.md) create a JSON value\n\n## Version history\n\n1. Since version 1.0.0.\n2. Since version 1.0.0.\n3. Since version 1.0.0.\n4. Since version 1.0.0.\n5. Since version 1.0.0.\n6. Since version 3.8.0.\n7. Since version 3.8.0.", "messages": null, "tools": null} {"id": "941848c870090e50", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/is_boolean.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 970, "sha256": "d6a36f4b6acf9f24a72321aa0ffb451d3be5b545bab52724a692bcf389ee3e56", "text": "#include \n#include \n\nusing json = nlohmann::json;\n\nint main()\n{\n // create JSON values\n json j_null;\n json j_boolean = true;\n json j_number_integer = 17;\n json j_number_unsigned_integer = 12345678987654321u;\n json j_number_float = 23.42;\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n json j_array = {1, 2, 4, 8, 16};\n json j_string = \"Hello, world\";\n json j_binary = json::binary({1, 2, 3});\n\n // call is_boolean()\n std::cout << std::boolalpha;\n std::cout << j_null.is_boolean() << '\\n';\n std::cout << j_boolean.is_boolean() << '\\n';\n std::cout << j_number_integer.is_boolean() << '\\n';\n std::cout << j_number_unsigned_integer.is_boolean() << '\\n';\n std::cout << j_number_float.is_boolean() << '\\n';\n std::cout << j_object.is_boolean() << '\\n';\n std::cout << j_array.is_boolean() << '\\n';\n std::cout << j_string.is_boolean() << '\\n';\n std::cout << j_binary.is_boolean() << '\\n';\n}", "messages": null, "tools": null} {"id": "95058f9f27d337d9", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/resolve/browser-field/relative.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 299, "sha256": "f8972400c679fc2a376dc3e29df8abedb41cea1bfa65ff94c5fc9111f1020b1e", "text": "/* eslint-disable import-x/no-duplicates */\nimport ra from './no-ext'\nimport rb from './no-ext.js' // no substitution\nimport rc from './ext'\nimport rd from './ext.js'\nimport re from './ext-index/index.js'\nimport rf from './no-ext-index/index.js' // no substitution\n\nexport { ra, rb, rc, rd, re, rf }", "messages": null, "tools": null} {"id": "95a7fe58a0fbfe3e", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/hmr/__tests__/hmr.spec.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 38646, "sha256": "f6c8cad769c8efb422505baca1919781350061975217ce1b3b10606d333d287e", "text": "import { stripVTControlCharacters } from 'node:util'\nimport { beforeAll, describe, expect, it, test } from 'vitest'\nimport type { Page } from 'playwright-chromium'\nimport {\n addFile,\n browser,\n browserLogs,\n editFile,\n getBg,\n getColor,\n isBuild,\n page,\n readFile,\n removeFile,\n serverLogs,\n untilBrowserLogAfter,\n viteTestUrl,\n} from '~utils'\n\ntest('should render', async () => {\n expect(await page.textContent('.app')).toBe('1')\n expect(await page.textContent('.dep')).toBe('1')\n expect(await page.textContent('.nested')).toBe('1')\n})\n\nif (!isBuild) {\n test('should connect', async () => {\n expect(browserLogs.length).toBe(5)\n expect(browserLogs.some((msg) => msg.includes('connected'))).toBe(true)\n browserLogs.length = 0\n })\n\n const fetchHotEvents = async (): Promise<{\n connectCount: number\n disconnectCount: number\n }> => {\n const res = await fetch(viteTestUrl + '/hot-events-counts')\n return res.json()\n }\n test('hot events', async () => {\n expect(await fetchHotEvents()).toStrictEqual({\n connectCount: 1,\n disconnectCount: 0,\n })\n await untilBrowserLogAfter(() => page.reload(), [/connected/])\n expect(await fetchHotEvents()).toStrictEqual({\n connectCount: 2,\n disconnectCount: 1,\n })\n })\n\n test('self accept', async () => {\n const el = await page.$('.app')\n await untilBrowserLogAfter(\n () =>\n editFile('hmr.ts', (code) =>\n code.replace('const foo = 1', 'const foo = 2 '),\n ),\n [\n '>>> vite:beforeUpdate -- update',\n 'foo was: 1',\n '(self-accepting 1) foo is now: 2',\n '(self-accepting 2) foo is now: 2',\n '[vite] hot updated: /hmr.ts',\n '>>> vite:afterUpdate -- update',\n ],\n true,\n )\n await expect.poll(() => el.textContent()).toMatch('2')\n\n await untilBrowserLogAfter(\n () =>\n editFile('hmr.ts', (code) =>\n code.replace('const foo = 2', 'const foo = 3 '),\n ),\n [\n '>>> vite:beforeUpdate -- update',\n 'foo was: 2',\n '(self-accepting 1) foo is now: 3',\n '(self-accepting 2) foo is now: 3',\n '[vite] hot updated: /hmr.ts',\n '>>> vite:afterUpdate -- update',\n ],\n true,\n )\n await expect.poll(() => el.textContent()).toMatch('3')\n })\n\n test('hot data persists across module instances', async () => {\n await untilBrowserLogAfter(\n () =>\n editFile('hotData.js', (code) =>\n code.replace('const value = 1', 'const value = 2 '),\n ),\n [\n '>>> vite:beforeUpdate -- update',\n '(hot data) value from execution: 1',\n '(hot data) value from dispose: 1',\n '[vite] hot updated: /hotData.js',\n '>>> vite:afterUpdate -- update',\n ],\n true,\n )\n\n await untilBrowserLogAfter(\n () =>\n editFile('hotData.js', (code) =>\n code.replace('const value = 2', 'const value = 3 '),\n ),\n [\n '>>> vite:beforeUpdate -- update',\n '(hot data) value from execution: 2',\n '(hot data) value from dispose: 2',\n '[vite] hot updated: /hotData.js',\n '>>> vite:afterUpdate -- update',\n ],\n true,\n )\n })\n\n test('accept dep', async () => {\n const el = await page.$('.dep')\n await untilBrowserLogAfter(\n () =>\n editFile('hmrDep.js', (code) =>\n code.replace('const foo = 1', 'const foo = 2 '),\n ),\n [\n '>>> vite:beforeUpdate -- update',\n '(dep) foo was: 1',\n '(dep) foo from dispose: 1',\n '(single dep) foo is now: 2',\n '(single dep) nested foo is now: 1',\n '(multi deps) foo is now: 2',\n '(multi deps) nested foo is now: 1',\n '[vite] hot updated: /hmrDep.js via /hmr.ts',\n '>>> vite:afterUpdate -- update',\n ],\n true,\n )\n await expect.poll(() => el.textContent()).toMatch('2')\n\n await untilBrowserLogAfter(\n () =>\n editFile('hmrDep.js', (code) =>\n code.replace('const foo = 2', 'const foo = 3 '),\n ),\n [\n '>>> vite:beforeUpdate -- update',\n '(dep) foo was: 2',\n '(dep) foo from dispose: 2',\n '(single dep) foo is now: 3',\n '(single dep) nested foo is now: 1',\n '(multi deps) foo is now: 3',\n '(multi deps) nested foo is now: 1',\n '[vite] hot updated: /hmrDep.js via /hmr.ts',\n '>>> vite:afterUpdate -- update',\n ],\n true,\n )\n await expect.poll(() => el.textContent()).toMatch('3')\n })\n\n test('nested dep propagation', async () => {\n const el = await page.$('.nested')\n await untilBrowserLogAfter(\n () =>\n editFile('hmrNestedDep.js', (code) =>\n code.replace('const foo = 1', 'const foo = 2 '),\n ),\n [\n '>>> vite:beforeUpdate -- update',\n '(dep) foo was: 3',\n '(dep) foo from dispose: 3',\n '(single dep) foo is now: 3',\n '(single dep) nested foo is now: 2',\n '(multi deps) foo is now: 3',\n '(multi deps) nested foo is now: 2',\n '[vite] hot updated: /hmrDep.js via /hmr.ts',\n '>>> vite:afterUpdate -- update',\n ],\n true,\n )\n await expect.poll(() => el.textContent()).toMatch('2')\n\n await untilBrowserLogAfter(\n () =>\n editFile('hmrNestedDep.js', (code) =>\n code.replace('const foo = 2', 'const foo = 3 '),\n ),\n [\n '>>> vite:beforeUpdate -- update',\n '(dep) foo was: 3',\n '(dep) foo from dispose: 3',\n '(single dep) foo is now: 3',\n '(single dep) nested foo is now: 3',\n '(multi deps) foo is now: 3',\n '(multi deps) nested foo is now: 3',\n '[vite] hot updated: /hmrDep.js via /hmr.ts',\n '>>> vite:afterUpdate -- update',\n ],\n true,\n )\n await expect.poll(() => el.textContent()).toMatch('3')\n })\n\n test('invalidate', async () => {\n const el = await page.$('.invalidation-parent')\n await untilBrowserLogAfter(\n () =>\n editFile('invalidation/child.js', (code) =>\n code.replace('child', 'child updated'),\n ),\n [\n '>>> vite:beforeUpdate -- update',\n '>>> vite:invalidate -- /invalidation/child.js',\n '[vite] invalidate /invalidation/child.js',\n '[vite] hot updated: /invalidation/child.js',\n '>>> vite:afterUpdate -- update',\n '>>> vite:beforeUpdate -- update',\n '(invalidation) parent is executing',\n '[vite] hot updated: /invalidation/parent.js',\n '>>> vite:afterUpdate -- update',\n ],\n true,\n )\n await expect.poll(() => el.textContent()).toMatch('child updated')\n })\n\n test('invalidate works with multiple tabs', async () => {\n let page2: Page\n try {\n page2 = await browser.newPage()\n await page2.goto(viteTestUrl)\n\n const el = await page.$('.invalidation-parent')\n await untilBrowserLogAfter(\n () =>\n editFile('invalidation/child.js', (code) =>\n code.replace('child', 'child updated'),\n ),\n [\n '>>> vite:beforeUpdate -- update',\n '>>> vite:invalidate -- /invalidation/child.js',\n '[vite] invalidate /invalidation/child.js',\n '[vite] hot updated: /invalidation/child.js',\n '>>> vite:afterUpdate -- update',\n // if invalidate dedupe doesn't work correctly, this beforeUpdate will be called twice\n '>>> vite:beforeUpdate -- update',\n '(invalidation) parent is executing',\n '[vite] hot updated: /invalidation/parent.js',\n '>>> vite:afterUpdate -- update',\n ],\n true,\n )\n await expect.poll(() => el.textContent()).toMatch('child updated')\n } finally {\n await page2.close()\n }\n })\n\n test('invalidate on root triggers page reload', async () => {\n editFile('invalidation/root.js', (code) => code.replace('Init', 'Updated'))\n await page.waitForEvent('load')\n await expect\n .poll(async () => (await page.$('.invalidation-root')).textContent())\n .toMatch('Updated')\n })\n\n test('soft invalidate', async () => {\n const el = await page.$('.soft-invalidation')\n expect(await el.textContent()).toBe(\n 'soft-invalidation/index.js is transformed 1 times. child is bar',\n )\n editFile('soft-invalidation/child.js', (code) =>\n code.replace('bar', 'updated'),\n )\n await expect\n .poll(() => el.textContent())\n .toBe(\n 'soft-invalidation/index.js is transformed 1 times. child is updated',\n )\n\n editFile('soft-invalidation/index.js', (code) =>\n code.replace('child is', 'child is now'),\n )\n editFile('soft-invalidation/child.js', (code) =>\n code.replace('updated', 'updated?'),\n )\n await expect\n .poll(() => el.textContent())\n .toBe(\n 'soft-invalidation/index.js is transformed 2 times. child is now updated?',\n )\n })\n\n test('invalidate in circular dep should not trigger infinite HMR', async () => {\n const el = await page.$('.invalidation-circular-deps')\n await expect.poll(() => el.textContent()).toMatch('child')\n editFile(\n 'invalidation-circular-deps/circular-invalidate/child.js',\n (code) => code.replace('child', 'child updated'),\n )\n await page.waitForEvent('load')\n await expect\n .poll(() => page.textContent('.invalidation-circular-deps'))\n .toMatch('child updated')\n })\n\n test('invalidate in circular dep should be hot updated if possible', async () => {\n const el = await page.$('.invalidation-circular-deps-handled')\n await expect.poll(() => el.textContent()).toMatch('child')\n editFile(\n 'invalidation-circular-deps/invalidate-handled-in-circle/child.js',\n (code) => code.replace('child', 'child updated'),\n )\n await expect.poll(() => el.textContent()).toMatch('child updated')\n })\n\n test('plugin hmr handler + custom event', async () => {\n const el = await page.$('.custom')\n editFile('customFile.js', (code) => code.replace('custom', 'edited2'))\n await expect.poll(() => el.textContent()).toMatch('edited2')\n })\n\n test('plugin hmr remove custom events', async () => {\n const el = await page.$('.toRemove')\n await expect.poll(() => el.textContent()).toMatch('edited2')\n editFile('customFile.js', (code) => code.replace('edited2', 'custom33'))\n await expect.poll(() => el.textContent()).toMatch('edited2')\n })\n\n test('plugin client-server communication', async () => {\n const el = await page.$('.custom-communication')\n await expect.poll(() => el.textContent()).toMatch('3')\n })\n\n test('full-reload encodeURI path', async () => {\n await page.goto(\n viteTestUrl + '/unicode-path/中文-にほんご-한글-🌕🌖🌗/index.html',\n )\n const el = await page.$('#app')\n expect(await el.textContent()).toBe('title')\n editFile('unicode-path/中文-にほんご-한글-🌕🌖🌗/index.html', (code) =>\n code.replace('title', 'title2'),\n )\n await page.waitForEvent('load')\n await expect\n .poll(async () => (await page.$('#app')).textContent())\n .toBe('title2')\n })\n\n test('CSS update preserves query params', async () => {\n await page.goto(viteTestUrl)\n\n editFile('global.css', (code) => code.replace('white', 'tomato'))\n\n const elprev = await page.$('.css-prev')\n const elpost = await page.$('.css-post')\n await expect.poll(() => elprev.textContent()).toMatch('param=required')\n await expect.poll(() => elpost.textContent()).toMatch('param=required')\n const textprev = await elprev.textContent()\n const textpost = await elpost.textContent()\n expect(textprev).not.toBe(textpost)\n expect(textprev).not.toMatch('direct')\n expect(textpost).not.toMatch('direct')\n })\n\n test('it swaps out link tags', async () => {\n await page.goto(viteTestUrl)\n\n editFile('global.css', (code) => code.replace('tomato', 'white'))\n\n let el = await page.$('.link-tag-added')\n await expect.poll(() => el.textContent()).toMatch('yes')\n\n el = await page.$('.link-tag-removed')\n await expect.poll(() => el.textContent()).toMatch('yes')\n\n await expect.poll(async () => (await page.$$('link')).length).toBe(1)\n })\n\n test('not loaded dynamic import', async () => {\n await page.goto(viteTestUrl + '/counter/index.html', { waitUntil: 'load' })\n\n let btn = await page.$('button')\n expect(await btn.textContent()).toBe('Counter 0')\n await btn.click()\n expect(await btn.textContent()).toBe('Counter 1')\n\n // Modifying `index.ts` triggers a page reload, as expected\n const indexTsLoadPromise = page.waitForEvent('load')\n editFile('counter/index.ts', (code) => code + '\\n')\n await indexTsLoadPromise\n btn = await page.$('button')\n expect(await btn.textContent()).toBe('Counter 0')\n\n await btn.click()\n expect(await btn.textContent()).toBe('Counter 1')\n\n // #7561\n // `dep.ts` defines `import.module.hot.accept` and has not been loaded.\n // Therefore, modifying it has no effect (doesn't trigger a page reload).\n // (Note that, a dynamic import that is never loaded and that does not\n // define `accept.module.hot.accept` may wrongfully trigger a full page\n // reload, see discussion at #7561.)\n const depTsLoadPromise = page.waitForEvent('load', { timeout: 1000 })\n editFile('counter/dep.ts', (code) => code + ' ')\n await expect(depTsLoadPromise).rejects.toThrow(\n /page\\.waitForEvent: Timeout \\d+ms exceeded while waiting for event \"load\"/,\n )\n\n btn = await page.$('button')\n expect(await btn.textContent()).toBe('Counter 1')\n })\n\n // #2255\n test('importing reloaded', async () => {\n await page.goto(viteTestUrl)\n const outputEle = await page.$('.importing-reloaded')\n const getOutput = () => {\n return outputEle.innerHTML()\n }\n\n await expect\n .poll(getOutput)\n .toMatch(['a.js: a0', 'b.js: b0,a0'].join('
'))\n\n editFile('importing-updated/a.js', (code) => code.replace(\"'a0'\", \"'a1' \"))\n await expect\n .poll(getOutput)\n .toMatch(['a.js: a0', 'b.js: b0,a0', 'a.js: a1'].join('
'))\n\n editFile('importing-updated/b.js', (code) =>\n code.replace('`b0,${a}`', '`b1,${a}` '),\n )\n // note that \"a.js: a1\" should not happen twice after \"b.js: b0,a0'\"\n await expect\n .poll(getOutput)\n .toMatch(\n ['a.js: a0', 'b.js: b0,a0', 'a.js: a1', 'b.js: b1,a1'].join('
'),\n )\n })\n\n describe('acceptExports', () => {\n const HOT_UPDATED = /hot updated/\n const CONNECTED = /connected/\n\n const baseDir = 'accept-exports'\n\n describe('when all used exports are accepted', () => {\n const testDir = baseDir + '/main-accepted'\n\n const fileName = 'target.ts'\n const file = `${testDir}/${fileName}`\n const url = '/' + file\n\n let dep = 'dep0'\n\n beforeAll(async () => {\n await untilBrowserLogAfter(\n () => page.goto(`${viteTestUrl}/${testDir}/`),\n [CONNECTED, />>>>>>/],\n (logs) => {\n expect(logs).toContain(`<<<<<< A0 B0 D0 ; ${dep}`)\n expect(logs).toContain('>>>>>> A0 D0')\n },\n )\n })\n\n it('the callback is called with the new version the module', async () => {\n const callbackFile = `${testDir}/callback.ts`\n const callbackUrl = '/' + callbackFile\n\n await untilBrowserLogAfter(\n () => {\n editFile(callbackFile, (code) =>\n code\n .replace(\"x = 'X'\", \"x = 'Y'\")\n .replace('reloaded >>>', 'reloaded (2) >>>'),\n )\n },\n HOT_UPDATED,\n (logs) => {\n expect(logs).toEqual([\n 'reloaded >>> Y',\n `[vite] hot updated: ${callbackUrl}`,\n ])\n },\n )\n\n await untilBrowserLogAfter(\n () => {\n editFile(callbackFile, (code) =>\n code.replace(\"x = 'Y'\", \"x = 'Z' \"),\n )\n },\n HOT_UPDATED,\n (logs) => {\n expect(logs).toEqual([\n 'reloaded (2) >>> Z',\n `[vite] hot updated: ${callbackUrl}`,\n ])\n },\n )\n })\n\n it('stops HMR bubble on dependency change', async () => {\n const depFileName = 'dep.ts'\n const depFile = `${testDir}/${depFileName}`\n\n await untilBrowserLogAfter(\n () => {\n editFile(\n depFile,\n (code) => code.replace('dep0', (dep = 'dep1')) + '\\n',\n )\n },\n HOT_UPDATED,\n (logs) => {\n expect(logs).toEqual([\n `<<<<<< A0 B0 D0 ; ${dep}`,\n `[vite] hot updated: ${url}`,\n ])\n },\n )\n })\n\n it('accepts itself and refreshes on change', async () => {\n await untilBrowserLogAfter(\n () => {\n editFile(file, (code) => code.replace(/(\\b[A-Z])0/g, '$11') + '\\n')\n },\n HOT_UPDATED,\n (logs) => {\n expect(logs).toEqual([\n `<<<<<< A1 B1 D1 ; ${dep}`,\n `[vite] hot updated: ${url}`,\n ])\n },\n )\n })\n\n it('accepts itself and refreshes on 2nd change', async () => {\n await untilBrowserLogAfter(\n () => {\n editFile(\n file,\n (code) =>\n code\n .replace(/(\\b[A-Z])1/g, '$12')\n .replace(\n \"acceptExports(['a', 'default']\",\n \"acceptExports(['b', 'default']\",\n ) + '\\n',\n )\n },\n HOT_UPDATED,\n (logs) => {\n expect(logs).toEqual([\n `<<<<<< A2 B2 D2 ; ${dep}`,\n `[vite] hot updated: ${url}`,\n ])\n },\n )\n })\n\n it('does not accept itself anymore after acceptedExports change', async () => {\n await untilBrowserLogAfter(\n async () => {\n editFile(file, (code) => code.replace(/(\\b[A-Z])2/g, '$13') + '\\n')\n await page.waitForEvent('load')\n },\n [CONNECTED, />>>>>>/],\n (logs) => {\n expect(logs).toContain(`<<<<<< A3 B3 D3 ; ${dep}`)\n expect(logs).toContain('>>>>>> A3 D3')\n },\n )\n })\n })\n\n describe('when some used exports are not accepted', () => {\n const testDir = baseDir + '/main-non-accepted'\n\n const namedFileName = 'named.ts'\n const namedFile = `${testDir}/${namedFileName}`\n const defaultFileName = 'default.ts'\n const defaultFile = `${testDir}/${defaultFileName}`\n const depFileName = 'dep.ts'\n const depFile = `${testDir}/${depFileName}`\n\n const a = 'A0'\n let dep = 'dep0'\n\n beforeAll(async () => {\n await untilBrowserLogAfter(\n () => page.goto(`${viteTestUrl}/${testDir}/`),\n [CONNECTED, />>>>>>/],\n (logs) => {\n expect(logs).toContain(`<<< named: ${a} ; ${dep}`)\n expect(logs).toContain(`<<< default: def0`)\n expect(logs).toContain(`>>>>>> ${a} def0`)\n },\n )\n })\n\n it('does not stop the HMR bubble on change to dep', async () => {\n await untilBrowserLogAfter(\n async () => {\n editFile(\n depFile,\n (code) => code.replace('dep0', (dep = 'dep1')) + '\\n',\n )\n await page.waitForEvent('load')\n },\n [CONNECTED, />>>>>>/],\n (logs) => {\n expect(logs).toContain(`<<< named: ${a} ; ${dep}`)\n },\n )\n })\n\n describe('does not stop the HMR bubble on change to self', () => {\n it('with named exports', async () => {\n await untilBrowserLogAfter(\n async () => {\n editFile(namedFile, (code) => code.replace(a, 'A1') + '\\n')\n await page.waitForEvent('load')\n },\n [CONNECTED, />>>>>>/],\n (logs) => {\n expect(logs).toContain(`<<< named: A1 ; ${dep}`)\n },\n )\n })\n\n it('with default export', async () => {\n await untilBrowserLogAfter(\n async () => {\n editFile(\n defaultFile,\n (code) => code.replace('def0', 'def1') + '\\n',\n )\n await page.waitForEvent('load')\n },\n [CONNECTED, />>>>>>/],\n (logs) => {\n expect(logs).toContain(`<<< default: def1`)\n },\n )\n })\n })\n })\n\n test('accepts itself when imported for side effects only (no bindings imported)', async () => {\n const testDir = baseDir + '/side-effects'\n const file = 'side-effects.ts'\n\n await untilBrowserLogAfter(\n () => page.goto(`${viteTestUrl}/${testDir}/`),\n [CONNECTED, />>>/],\n (logs) => {\n expect(logs).toContain('>>> side FX')\n },\n )\n\n await untilBrowserLogAfter(\n () => {\n editFile(`${testDir}/${file}`, (code) =>\n code.replace('>>> side FX', '>>> side FX !!'),\n )\n },\n HOT_UPDATED,\n (logs) => {\n expect(logs).toEqual([\n '>>> side FX !!',\n `[vite] hot updated: /${testDir}/${file}`,\n ])\n },\n )\n })\n\n describe('acceptExports([])', () => {\n const testDir = baseDir + '/unused-exports'\n\n test('accepts itself if no exports are imported', async () => {\n const fileName = 'unused.ts'\n const file = `${testDir}/${fileName}`\n const url = '/' + file\n\n await untilBrowserLogAfter(\n () => page.goto(`${viteTestUrl}/${testDir}/`),\n [CONNECTED, '-- unused --'],\n (logs) => {\n expect(logs).toContain('-- unused --')\n },\n )\n\n await untilBrowserLogAfter(\n () => {\n editFile(\n file,\n (code) => code.replace('-- unused --', '-> unused <-') + '\\n',\n )\n },\n HOT_UPDATED,\n (logs) => {\n expect(logs).toEqual(['-> unused <-', `[vite] hot updated: ${url}`])\n },\n )\n })\n\n test(\"doesn't accept itself if any of its exports is imported\", async () => {\n const fileName = 'used.ts'\n const file = `${testDir}/${fileName}`\n\n await untilBrowserLogAfter(\n () => page.goto(`${viteTestUrl}/${testDir}/`),\n [CONNECTED, '-- used --'],\n (logs) => {\n expect(logs).toContain('-- used --')\n expect(logs).toContain('used:foo0')\n },\n )\n\n await untilBrowserLogAfter(\n async () => {\n editFile(\n file,\n (code) =>\n code\n .replace('foo0', 'foo1')\n .replace('-- used --', '-> used <-') + '\\n',\n )\n await page.waitForEvent('load')\n },\n [CONNECTED, /used:foo/],\n (logs) => {\n expect(logs).toContain('-> used <-')\n expect(logs).toContain('used:foo1')\n },\n )\n })\n })\n\n describe('indiscriminate imports: import *', () => {\n const testStarExports = (testDirName: string) => {\n const testDir = `${baseDir}/${testDirName}`\n\n it('accepts itself if all its exports are accepted', async () => {\n const fileName = 'deps-all-accepted.ts'\n const file = `${testDir}/${fileName}`\n const url = '/' + file\n\n await untilBrowserLogAfter(\n () => page.goto(`${viteTestUrl}/${testDir}/`),\n [CONNECTED, '>>> ready <<<'],\n (logs) => {\n expect(logs).toContain('loaded:all:a0b0c0default0')\n expect(logs).toContain('all >>>>>> a0, b0, c0')\n },\n )\n\n await untilBrowserLogAfter(\n () => {\n editFile(file, (code) => code.replace(/([abc])0/g, '$11') + '\\n')\n },\n HOT_UPDATED,\n (logs) => {\n expect(logs).toEqual([\n 'all >>>>>> a1, b1, c1',\n `[vite] hot updated: ${url}`,\n ])\n },\n )\n\n await untilBrowserLogAfter(\n () => {\n editFile(file, (code) => code.replace(/([abc])1/g, '$12') + '\\n')\n },\n HOT_UPDATED,\n (logs) => {\n expect(logs).toEqual([\n 'all >>>>>> a2, b2, c2',\n `[vite] hot updated: ${url}`,\n ])\n },\n )\n })\n\n it(\"doesn't accept itself if one export is not accepted\", async () => {\n const fileName = 'deps-some-accepted.ts'\n const file = `${testDir}/${fileName}`\n\n await untilBrowserLogAfter(\n () => page.goto(`${viteTestUrl}/${testDir}/`),\n [CONNECTED, '>>> ready <<<'],\n (logs) => {\n expect(logs).toContain('loaded:some:a0b0c0default0')\n expect(logs).toContain('some >>>>>> a0, b0, c0')\n },\n )\n\n await untilBrowserLogAfter(\n async () => {\n const loadPromise = page.waitForEvent('load')\n editFile(file, (code) => code.replace(/([abc])0/g, '$11') + '\\n')\n await loadPromise\n },\n [CONNECTED, '>>> ready <<<'],\n (logs) => {\n expect(logs).toContain('loaded:some:a1b1c1default0')\n expect(logs).toContain('some >>>>>> a1, b1, c1')\n },\n )\n })\n }\n\n describe('import * from ...', () => testStarExports('star-imports'))\n\n describe('dynamic import(...)', () => testStarExports('dynamic-imports'))\n })\n })\n\n test('css in html hmr', async () => {\n await page.goto(viteTestUrl)\n expect(await getBg('.import-image')).toMatch('icon')\n await page.goto(viteTestUrl + '/foo/', { waitUntil: 'load' })\n expect(await getBg('.import-image')).toMatch('icon')\n\n const loadPromise = page.waitForEvent('load')\n editFile('index.html', (code) => code.replace(\"url('./icon.png')\", ''))\n await loadPromise\n expect(await getBg('.import-image')).toMatch('')\n })\n\n test('HTML', async () => {\n await page.goto(viteTestUrl + '/counter/index.html')\n let btn = await page.$('button')\n expect(await btn.textContent()).toBe('Counter 0')\n\n const loadPromise = page.waitForEvent('load')\n editFile('counter/index.html', (code) =>\n code.replace('Counter', 'Compteur'),\n )\n await loadPromise\n btn = await page.$('button')\n expect(await btn.textContent()).toBe('Compteur 0')\n })\n\n test('handle virtual module updates', async () => {\n await page.goto(viteTestUrl)\n const el = await page.$('.virtual')\n expect(await el.textContent()).toBe('[success]0')\n editFile('importedVirtual.js', (code) => code.replace('[success]', '[wow]'))\n await expect\n .poll(async () => {\n const el = await page.$('.virtual')\n return await el.textContent()\n })\n .toBe('[wow]0')\n })\n\n test('invalidate virtual module', async () => {\n await page.goto(viteTestUrl)\n const el = await page.$('.virtual')\n expect(await el.textContent()).toBe('[wow]0')\n const btn = await page.$('.virtual-update')\n btn.click()\n await expect\n .poll(async () => {\n const el = await page.$('.virtual')\n return await el.textContent()\n })\n .toBe('[wow]1')\n })\n\n test('handle virtual module accept updates', async () => {\n await page.goto(viteTestUrl)\n const el = await page.$('.virtual-dep')\n expect(await el.textContent()).toBe('0')\n editFile('importedVirtual.js', (code) => code.replace('[wow]', '[wow2]'))\n await expect\n .poll(async () => {\n const el = await page.$('.virtual-dep')\n return await el.textContent()\n })\n .toBe('[wow2]0')\n })\n\n test('invalidate virtual module and accept', async () => {\n await page.goto(viteTestUrl)\n const el = await page.$('.virtual-dep')\n expect(await el.textContent()).toBe('0')\n const btn = await page.$('.virtual-update-dep')\n btn.click()\n await expect\n .poll(async () => {\n const el = await page.$('.virtual-dep')\n return await el.textContent()\n })\n .toBe('[wow2]2')\n })\n\n test('keep hmr reload after missing import on server startup', async () => {\n const file = 'missing-import/a.js'\n const importCode = \"import 'missing-modules'\"\n const unImportCode = `// ${importCode}`\n\n await untilBrowserLogAfter(\n () =>\n page.goto(viteTestUrl + '/missing-import/index.html', {\n waitUntil: 'load',\n }),\n /connected/, // wait for HMR connection\n )\n\n await untilBrowserLogAfter(async () => {\n const loadPromise = page.waitForEvent('load')\n editFile(file, (code) => code.replace(importCode, unImportCode))\n await loadPromise\n }, ['missing test', /connected/])\n\n await untilBrowserLogAfter(async () => {\n const loadPromise = page.waitForEvent('load')\n editFile(file, (code) => code.replace(unImportCode, importCode))\n await loadPromise\n }, [/500/, /connected/])\n })\n\n test('should hmr when file is deleted and restored', async () => {\n await page.goto(viteTestUrl)\n\n const parentFile = 'file-delete-restore/parent.js'\n const childFile = 'file-delete-restore/child.js'\n\n await expect\n .poll(() => page.textContent('.file-delete-restore'))\n .toMatch('parent:child')\n\n editFile(childFile, (code) =>\n code.replace(\"value = 'child'\", \"value = 'child1'\"),\n )\n await expect\n .poll(() => page.textContent('.file-delete-restore'))\n .toMatch('parent:child1')\n\n // delete the file\n editFile(parentFile, (code) =>\n code.replace(\n \"export { value as childValue } from './child'\",\n \"export const childValue = 'not-child'\",\n ),\n )\n const originalChildFileCode = readFile(childFile)\n await Promise.all([\n untilBrowserLogAfter(\n () => removeFile(childFile),\n `${childFile} is disposed`,\n ),\n expect\n .poll(() => page.textContent('.file-delete-restore'))\n .toMatch('parent:not-child'),\n ])\n\n await untilBrowserLogAfter(async () => {\n const loadPromise = page.waitForEvent('load')\n addFile(childFile, originalChildFileCode)\n editFile(parentFile, (code) =>\n code.replace(\n \"export const childValue = 'not-child'\",\n \"export { value as childValue } from './child'\",\n ),\n )\n await loadPromise\n }, [/connected/])\n await expect\n .poll(() => page.textContent('.file-delete-restore'))\n .toMatch('parent:child')\n })\n\n test('delete file should not break hmr', async () => {\n await page.goto(viteTestUrl)\n\n await expect\n .poll(() => page.textContent('.intermediate-file-delete-display'))\n .toMatch('count is 1')\n\n // add state\n await page.click('.intermediate-file-delete-increment')\n await expect\n .poll(() => page.textContent('.intermediate-file-delete-display'))\n .toMatch('count is 2')\n\n // update import, hmr works\n editFile('intermediate-file-delete/index.js', (code) =>\n code.replace(\"from './re-export.js'\", \"from './display.js'\"),\n )\n editFile('intermediate-file-delete/display.js', (code) =>\n code.replace('count is ${count}', 'count is ${count}!'),\n )\n await expect\n .poll(() => page.textContent('.intermediate-file-delete-display'))\n .toMatch('count is 2!')\n\n // remove unused file, page reload because it's considered entry point now\n removeFile('intermediate-file-delete/re-export.js')\n await expect\n .poll(() => page.textContent('.intermediate-file-delete-display'))\n .toMatch('count is 1!')\n\n // re-add state\n await page.click('.intermediate-file-delete-increment')\n await expect\n .poll(() => page.textContent('.intermediate-file-delete-display'))\n .toMatch('count is 2!')\n\n // hmr works after file deletion\n editFile('intermediate-file-delete/display.js', (code) =>\n code.replace('count is ${count}!', 'count is ${count}'),\n )\n await expect\n .poll(() => page.textContent('.intermediate-file-delete-display'))\n .toMatch('count is 2')\n })\n\n test('deleted file should trigger dispose and prune callbacks', async () => {\n await page.goto(viteTestUrl)\n\n const parentFile = 'file-delete-restore/parent.js'\n const childFile = 'file-delete-restore/child.js'\n const originalChildFileCode = readFile(childFile)\n\n await untilBrowserLogAfter(\n () => {\n // delete the file\n editFile(parentFile, (code) =>\n code.replace(\n \"export { value as childValue } from './child'\",\n \"export const childValue = 'not-child'\",\n ),\n )\n removeFile(childFile)\n },\n [\n 'file-delete-restore/child.js is disposed',\n 'file-delete-restore/child.js is pruned',\n ],\n false,\n )\n await expect\n .poll(() => page.textContent('.file-delete-restore'))\n .toMatch('parent:not-child')\n\n // restore the file\n await untilBrowserLogAfter(() => {\n addFile(childFile, originalChildFileCode)\n editFile(parentFile, (code) =>\n code.replace(\n \"export const childValue = 'not-child'\",\n \"export { value as childValue } from './child'\",\n ),\n )\n }, 'file-delete-restore/child.js hot data after prune: undefined')\n await expect\n .poll(() => page.textContent('.file-delete-restore'))\n .toMatch('parent:child')\n })\n\n test('deleting import from non-self-accepting module can trigger prune event', async () => {\n await page.goto(viteTestUrl)\n await expect.poll(() => page.textContent('.prune')).toMatch('prune-init')\n editFile('prune/dep1.js', (code) =>\n code.replace(`import './dep2.js'`, `// import './dep2.js'`),\n )\n // Prune is triggered when there are other dependencies.\n await expect\n .poll(() => page.textContent('.prune'))\n .toMatch('prune-init|dep2-disposed|dep2-pruned')\n editFile('prune/dep1.js', (code) =>\n code.replace(`import './dep3.js'`, `// import './dep3.js'`),\n )\n // Prune is triggered when there are no more dependencies.\n await expect\n .poll(() => page.textContent('.prune'))\n .toMatch('prune-init|dep2-disposed|dep2-pruned|dep3-disposed|dep3-pruned')\n })\n\n test('import.meta.hot?.accept', async () => {\n await page.goto(viteTestUrl)\n\n const el = await page.$('.optional-chaining')\n await untilBrowserLogAfter(\n () =>\n editFile(\n 'optional-chaining/child.js',\n (code) => code.replace('const foo = 1', 'const foo = 2') + '\\n',\n ),\n '(optional-chaining) child update',\n )\n await expect.poll(() => el.textContent()).toMatch('2')\n })\n\n test('hmr works for self-accepted module within circular imported files', async () => {\n await page.goto(viteTestUrl + '/self-accept-within-circular/index.html')\n const el = await page.$('.self-accept-within-circular')\n expect(await el.textContent()).toBe('c')\n const lastServerLogIndex = serverLogs.length\n editFile('self-accept-within-circular/c.js', (code) =>\n code.replace(`export const c = 'c'`, `export const c = 'cc'`),\n )\n await expect\n .poll(() => page.textContent('.self-accept-within-circular'))\n .toBe('cc')\n // Should still keep hmr update, but it'll error on the browser-side and will refresh itself.\n expect(\n serverLogs.slice(lastServerLogIndex).map(stripVTControlCharacters),\n ).toContain('hmr update /self-accept-within-circular/c.js')\n })\n\n test('hmr should not reload if no accepted within circular imported files', async () => {\n await page.goto(viteTestUrl + '/circular/index.html')\n const el = await page.$('.circular')\n expect(await el.textContent()).toBe(\n 'mod-a -> mod-b -> mod-c -> mod-a (expected error)',\n )\n editFile('circular/mod-b.js', (code) =>\n code.replace(`mod-b ->`, `mod-b (edited) ->`),\n )\n await expect\n .poll(() => el.textContent())\n .toBe('mod-a -> mod-b (edited) -> mod-c -> mod-a (expected error)')\n })\n\n test('not inlined assets HMR', async () => {\n await page.goto(viteTestUrl)\n const el = await page.$('#logo-no-inline')\n await untilBrowserLogAfter(\n () =>\n editFile('logo-no-inline.svg', (code) =>\n code.replace('height=\"30px\"', 'height=\"40px\" '),\n ),\n /Logo-no-inline updated/,\n )\n await expect\n .poll(() => el.evaluate((it) => `${it.clientHeight}`))\n .toMatch('40')\n })\n\n test('inlined assets HMR', async () => {\n await page.goto(viteTestUrl)\n const el = await page.$('#logo')\n await untilBrowserLogAfter(\n () =>\n editFile('logo.svg', (code) =>\n code.replace('height=\"30px\"', 'height=\"40px\" '),\n ),\n /Logo updated/,\n )\n await expect\n .poll(() => el.evaluate((it) => `${it.clientHeight}`))\n .toMatch('40')\n })\n\n test('CSS HMR with this.addWatchFile', async () => {\n await page.goto(viteTestUrl + '/css-deps/index.html')\n expect(await getColor('.css-deps')).toBe('red')\n editFile('css-deps/dep.js', (code) => code.replace(`red`, `green`))\n await expect.poll(() => getColor('.css-deps')).toBe('green')\n })\n\n test('hmr should happen after missing file is created', async () => {\n const file = 'missing-file/a.js'\n const code = 'console.log(\"a.js\")'\n\n await untilBrowserLogAfter(\n () =>\n page.goto(viteTestUrl + '/missing-file/index.html', {\n waitUntil: 'load',\n }),\n /connected/, // wait for HMR connection\n )\n\n await untilBrowserLogAfter(async () => {\n const loadPromise = page.waitForEvent('load')\n addFile(file, code)\n await loadPromise\n }, [/connected/, 'a.js'])\n })\n\n test('deduplicate server rendered link stylesheet', async () => {\n await page.goto(viteTestUrl + '/css-link/index.html')\n await expect.poll(() => getColor('.test-css-link')).toBe('orange')\n\n // remove color\n editFile('css-link/styles.css', (code) =>\n code.replace('color: orange;', '/* removed */'),\n )\n await expect.poll(() => getColor('.test-css-link')).toBe('black')\n\n // add color\n editFile('css-link/styles.css', (code) =>\n code.replace('/* removed */', 'color: blue;'),\n )\n await expect.poll(() => getColor('.test-css-link')).toBe('blue')\n\n // // remove css import from js\n editFile('css-link/main.js', (code) =>\n code.replace(`import './styles.css'`, ``),\n )\n await expect.poll(() => getColor('.test-css-link')).toBe('black')\n })\n}", "messages": null, "tools": null} {"id": "95dd83066de4dcc4", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "include/nlohmann/detail/iterators/internal_iterator.hpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 1070, "sha256": "8a3597a86d0881a2a292519d875bab1cac40dea1c111dc472c415c37d270f005", "text": "// __ _____ _____ _____\n// __| | __| | | | JSON for Modern C++\n// | | |__ | | | | | | version 3.12.0\n// |_____|_____|_____|_|___| https://github.com/nlohmann/json\n//\n// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann \n// SPDX-License-Identifier: MIT\n\n#pragma once\n\n#include \n#include \n\nNLOHMANN_JSON_NAMESPACE_BEGIN\nnamespace detail\n{\n\n/*!\n@brief an iterator value\n\n@note This structure could easily be a union, but MSVC currently does not allow\nunions members with complex constructors, see https://github.com/nlohmann/json/pull/105.\n*/\ntemplate struct internal_iterator\n{\n /// iterator for JSON objects\n typename BasicJsonType::object_t::iterator object_iterator {};\n /// iterator for JSON arrays\n typename BasicJsonType::array_t::iterator array_iterator {};\n /// generic iterator for all other types\n primitive_iterator_t primitive_iterator {};\n};\n\n} // namespace detail\nNLOHMANN_JSON_NAMESPACE_END", "messages": null, "tools": null} {"id": "9639911859b04c7c", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/backend-integration/frontend/entrypoints/main.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 633, "sha256": "7631449297f7edc59620203bcc05c0ffde0a2e99a0f52a1d3abf66c0d2a5406a", "text": "import 'vite/modulepreload-polyfill'\nimport cssUrl from '../styles/url.css?url'\nimport waterContainer from './water-container.svg'\n\nconst cssLink = document.createElement('link')\ncssLink.rel = 'stylesheet'\ncssLink.href = cssUrl\ndocument.querySelector('head').prepend(cssLink)\n\nconst dummyMeta = document.createElement('meta')\ndummyMeta.name = 'dummy'\ndummyMeta.content = waterContainer\ndocument.querySelector('head').append(dummyMeta)\n\nexport const colorClass = 'text-black'\n\nexport function colorHeading() {\n document.querySelector('h1').className = colorClass\n}\n\ncolorHeading()\n\nif (import.meta.hot) {\n import.meta.hot.accept()\n}", "messages": null, "tools": null} {"id": "9653bd533155d292", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/merge_patch.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 1030, "sha256": "fc77cae10f85a3e08d1d7ee51b879e1a8b0ddc71227b7e357284404db167af7e", "text": "#include \n#include \n#include // for std::setw\n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nint main()\n{\n // the original document\n json document = R\"({\n \"title\": \"Goodbye!\",\n \"author\": {\n \"givenName\": \"John\",\n \"familyName\": \"Doe\"\n },\n \"tags\": [\n \"example\",\n \"sample\"\n ],\n \"content\": \"This will be unchanged\"\n })\"_json;\n\n // the patch\n json patch = R\"({\n \"title\": \"Hello!\",\n \"phoneNumber\": \"+01-123-456-7890\",\n \"author\": {\n \"familyName\": null\n },\n \"tags\": [\n \"example\"\n ]\n })\"_json;\n\n // apply the patch\n document.merge_patch(patch);\n\n // output original and patched document\n std::cout << std::setw(4) << document << std::endl;\n}", "messages": null, "tools": null} {"id": "968d1f6214dc1535", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/node/__tests_dts__/typeOptions.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 655, "sha256": "b9e618733d3e251a3a5f2de2c60a3833e6f9c63f7d7610974e9003d66c80454c", "text": "// This file tests `ViteTypeOptions` in `packages/vite/types/importMeta.d.ts`\nimport type { ExpectFalse, ExpectTrue } from '@type-challenges/utils'\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\ninterface TypeOptions1 {}\ninterface TypeOptions2 {\n strictImportMetaEnv: unknown\n}\ninterface TypeOptions3 {\n unknownKey: unknown\n}\n\ntype IsEnabled = Key extends keyof Opts ? true : false\n\nexport type cases = [\n ExpectFalse>,\n ExpectTrue>,\n ExpectFalse>,\n]\n\nexport {}", "messages": null, "tools": null} {"id": "96b2a5abcece564a", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/create-vite/template-lit-ts/src/index.css", "lang": "css", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 445, "sha256": "22e289cbff2ae388fd8fde707cb78d9b0453594309f86770da57a38773b6ec31", "text": ":root {\n color-scheme: light dark;\n background-color: #ffffff;\n}\n\n@media (prefers-color-scheme: dark) {\n :root {\n background-color: #16171d;\n }\n}\n\nbody {\n margin: 0;\n display: flex;\n justify-content: center;\n align-items: center;\n min-width: 320px;\n min-height: 100svh;\n font-synthesis: none;\n text-rendering: optimizeLegibility;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n overflow-x: hidden;\n}", "messages": null, "tools": null} {"id": "96d6c8c848f8db07", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/json_pointer__pop_front.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 421, "sha256": "c1ffa3232170e78a4d120ed4eab4f66c3e5d8c8e5a79b9bff105f1a493cf0039", "text": "#include \n#include \n\nusing json = nlohmann::json;\n\nint main()\n{\n // create empty JSON Pointer\n json::json_pointer ptr(\"/foo/bar/baz\");\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n // call pop_front()\n ptr.pop_front();\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n ptr.pop_front();\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n\n ptr.pop_front();\n std::cout << \"\\\"\" << ptr << \"\\\"\\n\";\n}", "messages": null, "tools": null} {"id": "978a00d573f1418d", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/node/__tests__/external.spec.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 957, "sha256": "f76d103d863dc14bd1a8007094d08fd3c354a01b3883defbf33c279b319986e8", "text": "import { fileURLToPath } from 'node:url'\nimport { describe, expect, test } from 'vitest'\nimport { resolveConfig } from '../config'\nimport { createIsConfiguredAsExternal } from '../external'\nimport { PartialEnvironment } from '../baseEnvironment'\n\ndescribe('createIsConfiguredAsExternal', () => {\n test('default', async () => {\n const isExternal = await createIsExternal()\n expect(isExternal('@vitejs/cjs-ssr-dep')).toBe(false)\n })\n\n test('force external', async () => {\n const isExternal = await createIsExternal(true)\n expect(isExternal('@vitejs/cjs-ssr-dep')).toBe(true)\n })\n})\n\nasync function createIsExternal(external?: true) {\n const resolvedConfig = await resolveConfig(\n {\n configFile: false,\n root: fileURLToPath(new URL('./', import.meta.url)),\n resolve: { external },\n },\n 'serve',\n )\n const environment = new PartialEnvironment('ssr', resolvedConfig)\n return createIsConfiguredAsExternal(environment)\n}", "messages": null, "tools": null} {"id": "97b0ccd0d5106164", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/thirdparty/Fuzzer/test/DivTest.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 487, "sha256": "be49b106e275e1422d6247dde20ed29b4bd166e930f5dfff7e4090ec1c00fbb1", "text": "// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n\n// Simple test for a fuzzer: find the interesting argument for div.\n#include \n#include \n#include \n#include \n#include \n\nstatic volatile int Sink;\n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {\n if (Size < 4) return 0;\n int a;\n memcpy(&a, Data, 4);\n Sink = 12345678 / (987654 - a);\n return 0;\n}", "messages": null, "tools": null} {"id": "97db57cfe2b3ffcf", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/create-vite/template-qwik-ts/src/app.tsx", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 3262, "sha256": "f602f1fe814869e2ef14d7daf230aa103a40e6985f5b0ad67188a6a348735f3e", "text": "import { component$, useSignal } from '@builder.io/qwik'\n\nimport qwikLogo from './assets/qwik.svg'\nimport viteLogo from './assets/vite.svg'\nimport heroImg from './assets/hero.png'\nimport './app.css'\n\nexport const App = component$(() => {\n const count = useSignal(0)\n\n return (\n <>\n
\n
\n \"\"\n \"Qwik\n \"Vite\n
\n
\n

Get started

\n

\n Edit src/app.tsx and save to test HMR\n

\n
\n \n
\n\n
\n\n
\n\n
\n
\n \n )\n})", "messages": null, "tools": null} {"id": "986b780515e3bb0f", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/api/basic_json/clear.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 1256, "sha256": "5c584e24b7b3e09eed1d289ed5d54f600a4f178ef16813181eeecf2e3aa7b8fb", "text": "# nlohmann::basic_json::clear\n\n```cpp\nvoid clear() noexcept;\n```\n\nClears the content of a JSON value and resets it to the default value as if [`basic_json(value_t)`](basic_json.md) would\nhave been called with the current value type from [`type()`](type.md):\n\n| Value type | initial value |\n|------------|----------------------|\n| null | `null` |\n| boolean | `false` |\n| string | `\"\"` |\n| number | `0` |\n| binary | An empty byte vector |\n| object | `{}` |\n| array | `[]` |\n\nHas the same effect as calling\n\n```.cpp\n*this = basic_json(type());\n```\n\n## Exception safety\n\nNo-throw guarantee: this function never throws exceptions.\n\n## Complexity\n\nLinear in the size of the JSON value.\n\n## Notes\n\nAll iterators, pointers, and references related to this container are invalidated.\n\n## Examples\n\n??? example\n\n The example below shows the effect of `clear()` to different\n JSON types.\n \n ```cpp\n --8<-- \"examples/clear.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/clear.output\"\n ```\n\n## Version history\n\n- Added in version 1.0.0.\n- Added support for binary types in version 3.8.0.", "messages": null, "tools": null} {"id": "98a2eed711e11380", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/node/ssr/runtime/__tests__/server-runtime.spec.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 19449, "sha256": "8ea933f240f8f1375f9992164091fcb296a5626fa3040ad71a4301201d1bf8ef", "text": "import { existsSync, readdirSync } from 'node:fs'\nimport { posix, resolve, win32 } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { setTimeout } from 'node:timers/promises'\nimport { describe, expect, it, vi } from 'vitest'\nimport { isWindows } from '../../../../shared/utils'\nimport type { ExternalFetchResult } from '../../../../shared/invokeMethods'\nimport { createServer } from '../../../server'\nimport {\n createRunnableDevEnvironment,\n isRunnableDevEnvironment,\n} from '../../../server/environments/runnableEnvironment'\nimport type { HMRLogger } from '../../../../../dist/node/module-runner'\nimport { createModuleRunnerTester } from './utils'\n\nconst _URL = URL\n\ndescribe('module runner initialization', async () => {\n const it = await createModuleRunnerTester({\n resolve: {\n external: ['tinyglobby'],\n noExternal: ['@oxc-project/runtime'],\n },\n })\n\n it('correctly runs ssr code', async ({ runner }) => {\n const mod = await runner.import('/fixtures/simple.js')\n expect(mod.test).toEqual('I am initialized')\n\n // loads the same module if id is a file url\n const fileUrl = new _URL('./fixtures/simple.js', import.meta.url)\n const mod2 = await runner.import(fileUrl.toString())\n expect(mod).toBe(mod2)\n\n // loads the same module if id is a file path\n const filePath = fileURLToPath(fileUrl)\n const mod3 = await runner.import(filePath)\n expect(mod).toBe(mod3)\n })\n\n it('can load virtual modules as an entry point', async ({ runner }) => {\n const mod = await runner.import('virtual:test')\n expect(mod.msg).toBe('virtual')\n\n // already resolved id works similar to `transformRequest`\n expect(await runner.import(`\\0virtual:normal`)).toMatchInlineSnapshot(`\n {\n \"default\": \"ok\",\n }\n `)\n\n // escaped virtual module id works\n expect(await runner.import(`/@id/__x00__virtual:normal`))\n .toMatchInlineSnapshot(`\n {\n \"default\": \"ok\",\n }\n `)\n\n // timestamp query works\n expect(await runner.import(`virtual:normal?t=${Date.now()}`))\n .toMatchInlineSnapshot(`\n {\n \"default\": \"ok\",\n }\n `)\n\n // other arbitrary queries don't work\n await expect(() =>\n runner.import('virtual:normal?abcd=1234'),\n ).rejects.toMatchObject({\n message: expect.stringContaining(\n 'Failed to load url virtual:normal?abcd=1234',\n ),\n })\n })\n\n it('css is loaded correctly', async ({ runner }) => {\n const css = await runner.import('/fixtures/test.css')\n expect(css.default).toBe(undefined)\n const module = await runner.import('/fixtures/test.module.css')\n expect(module).toMatchObject({\n default: {\n test: expect.stringMatching(/^_test_/),\n },\n test: expect.stringMatching(/^_test_/),\n })\n })\n\n it('assets are loaded correctly', async ({ runner }) => {\n const assets = await runner.import('/fixtures/assets.js')\n expect(assets).toMatchObject({\n mov: '/fixtures/assets/placeholder.mov',\n txt: '/fixtures/assets/placeholder.txt',\n png: '/fixtures/assets/placeholder.png',\n webp: '/fixtures/assets/placeholder.webp',\n })\n })\n\n it('ids with Vite queries are loaded correctly', async ({ runner }) => {\n const raw = await runner.import('/fixtures/simple.js?raw')\n expect(raw.default).toMatchInlineSnapshot(`\n \"export const test = 'I am initialized'\n\n import.meta.hot?.accept()\n \"\n `)\n const url = await runner.import('/fixtures/simple.js?url')\n expect(url.default).toMatchInlineSnapshot(`\"/fixtures/simple.js\"`)\n const inline = await runner.import('/fixtures/test.css?inline')\n expect(inline.default).toMatchInlineSnapshot(`\n \".test {\n color: red;\n }\n \"\n `)\n })\n\n it('modules with query strings are treated as different modules', async ({\n runner,\n }) => {\n const modSimple = await runner.import('/fixtures/simple.js')\n const modUrl = await runner.import('/fixtures/simple.js?url')\n expect(modSimple).not.toBe(modUrl)\n expect(modUrl.default).toBe('/fixtures/simple.js')\n })\n\n it('exports is not modifiable', async ({ runner }) => {\n const mod = await runner.import('/fixtures/simple.js')\n expect(Object.isSealed(mod)).toBe(true)\n expect(() => {\n mod.test = 'I am modified'\n }).toThrowErrorMatchingInlineSnapshot(\n `[TypeError: Cannot set property test of [object Module] which has only a getter]`,\n )\n expect(() => {\n delete mod.test\n }).toThrowErrorMatchingInlineSnapshot(\n `[TypeError: Cannot delete property 'test' of [object Module]]`,\n )\n expect(() => {\n Object.defineProperty(mod, 'test', { value: 'I am modified' })\n }).toThrowErrorMatchingInlineSnapshot(\n `[TypeError: Cannot redefine property: test]`,\n )\n expect(() => {\n mod.other = 'I am added'\n }).toThrowErrorMatchingInlineSnapshot(\n `[TypeError: Cannot add property other, object is not extensible]`,\n )\n })\n\n it('throws the same error', async ({ runner }) => {\n expect.assertions(3)\n const s = Symbol()\n try {\n await runner.import('/fixtures/has-error.js')\n } catch (e) {\n expect(e[s]).toBeUndefined()\n e[s] = true\n expect(e[s]).toBe(true)\n }\n\n try {\n await runner.import('/fixtures/has-error.js')\n } catch (e) {\n expect(e[s]).toBe(true)\n }\n })\n\n it('importing external cjs library checks exports', async ({ runner }) => {\n await expect(() => runner.import('/fixtures/cjs-external-non-existing.js'))\n .rejects.toThrowErrorMatchingInlineSnapshot(`\n [SyntaxError: [vite] Named export 'nonExisting' not found. The requested module '@vitejs/cjs-external' is a CommonJS module, which may not support all module.exports as named exports.\n CommonJS modules can always be imported via the default export, for example using:\n\n import pkg from '@vitejs/cjs-external';\n const {nonExisting} = pkg;\n ]\n `)\n // subsequent imports of the same external package should not throw if imports are correct\n await expect(\n runner.import('/fixtures/cjs-external-existing.js'),\n ).resolves.toMatchObject({\n result: 'world',\n })\n })\n\n it('importing external esm library checks exports', async ({ runner }) => {\n await expect(() =>\n runner.import('/fixtures/esm-external-non-existing.js'),\n ).rejects.toThrowErrorMatchingInlineSnapshot(\n `[SyntaxError: [vite] The requested module '@vitejs/esm-external' does not provide an export named 'nonExisting']`,\n )\n // subsequent imports of the same external package should not throw if imports are correct\n await expect(\n runner.import('/fixtures/esm-external-existing.js'),\n ).resolves.toMatchObject({\n result: 'world',\n })\n })\n\n it(\"dynamic import doesn't produce duplicates\", async ({ runner }) => {\n const mod = await runner.import('/fixtures/dynamic-import.js')\n const modules = await mod.initialize()\n // toBe checks that objects are actually the same, not just structurally\n // using toEqual here would be a mistake because it check the structural difference\n expect(modules.static).toBe(modules.dynamicProcessed)\n expect(modules.static).toBe(modules.dynamicRelative)\n expect(modules.static).toBe(modules.dynamicAbsolute)\n expect(modules.static).toBe(modules.dynamicAbsoluteExtension)\n expect(modules.static).toBe(modules.dynamicAbsoluteFull)\n expect(modules.static).toBe(modules.dynamicFileUrl)\n })\n\n it('correctly imports a virtual module', async ({ runner }) => {\n const mod = await runner.import('/fixtures/virtual.js')\n expect(mod.msg0).toBe('virtual0')\n expect(mod.msg).toBe('virtual')\n })\n\n it('importing package from node_modules', async ({ runner }) => {\n const mod = (await runner.import(\n '/fixtures/installed.js',\n )) as typeof import('tinyspy')\n const fn = mod.spy()\n fn()\n expect(fn.called).toBe(true)\n })\n\n it('importing native node package', async ({ runner }) => {\n const mod = await runner.import('/fixtures/native.js')\n expect(mod.readdirSync).toBe(readdirSync)\n expect(mod.existsSync).toBe(existsSync)\n })\n\n it('correctly resolves module url', async ({ runner, server }) => {\n const { meta } = await runner.import('/fixtures/basic')\n const basicUrl = new _URL('./fixtures/basic.js', import.meta.url).toString()\n expect(meta.url).toBe(basicUrl)\n\n const filename = meta.filename!\n const dirname = meta.dirname!\n\n if (isWindows) {\n const cwd = process.cwd()\n const drive = `${cwd[0].toUpperCase()}:\\\\`\n const root = server.config.root.replace(/\\\\/g, '/')\n\n expect(filename.startsWith(drive)).toBe(true)\n expect(dirname.startsWith(drive)).toBe(true)\n\n expect(filename).toBe(win32.join(root, '.\\\\fixtures\\\\basic.js'))\n expect(dirname).toBe(win32.join(root, '.\\\\fixtures'))\n } else {\n const root = server.config.root\n\n expect(posix.join(root, './fixtures/basic.js')).toBe(filename)\n expect(posix.join(root, './fixtures')).toBe(dirname)\n }\n })\n\n it(`no maximum call stack error ModuleRunner.isCircularImport`, async ({\n runner,\n }) => {\n // entry.js ⇔ entry-cyclic.js\n // ⇓\n // action.js\n const mod = await runner.import('/fixtures/cyclic/entry')\n await mod.setupCyclic()\n const action = await mod.importAction('/fixtures/cyclic/action')\n expect(action).toBeDefined()\n })\n\n it('this of the exported function should be undefined', async ({\n runner,\n }) => {\n const mod = await runner.import('/fixtures/no-this/importer.js')\n expect(mod.result).toBe(undefined)\n })\n\n it.for([\n '/fixtures/cyclic2/test1/index.js',\n '/fixtures/cyclic2/test2/index.js',\n '/fixtures/cyclic2/test3/index.js',\n '/fixtures/cyclic2/test4/index.js',\n ] as const)(`cyclic %s`, async (entry, { runner }) => {\n const mod = await runner.import(entry)\n expect({ ...mod }).toEqual({\n dep1: {\n ok: true,\n },\n dep2: {\n ok: true,\n },\n })\n })\n\n it(`cyclic invalid 1`, async ({ runner }) => {\n // Node also fails but with a different message\n // $ node packages/vite/src/node/ssr/runtime/__tests__/fixtures/cyclic2/test5/index.js\n // ReferenceError: Cannot access 'dep1' before initialization\n await expect(() =>\n runner.import('/fixtures/cyclic2/test5/index.js'),\n ).rejects.toMatchInlineSnapshot(\n `[TypeError: Cannot read properties of undefined (reading 'ok')]`,\n )\n })\n\n it(`cyclic invalid 2`, async ({ runner }) => {\n // It should be an error but currently `undefined` fallback.\n expect(\n await runner.import('/fixtures/cyclic2/test6/index.js'),\n ).toMatchInlineSnapshot(\n `\n {\n \"dep1\": \"dep1: dep2: undefined\",\n }\n `,\n )\n })\n\n it(`cyclic with mixed import and re-export`, async ({ runner }) => {\n const mod = await runner.import('/fixtures/cyclic2/test7/Ion.js')\n expect(mod).toMatchInlineSnapshot(`\n {\n \"IonTypes\": {\n \"BLOB\": \"Blob\",\n },\n \"dom\": {\n \"Blob\": \"Blob\",\n },\n }\n `)\n })\n\n it(`execution order with mixed import and re-export`, async ({\n runner,\n onTestFinished,\n }) => {\n const spy = vi.spyOn(console, 'log').mockImplementation(() => {})\n onTestFinished(() => spy.mockRestore())\n\n await runner.import('/fixtures/execution-order-re-export/index.js')\n expect(spy.mock.calls.map((v) => v[0])).toMatchInlineSnapshot(`\n [\n \"dep1\",\n \"dep2\",\n ]\n `)\n })\n\n it(`live binding (export default function f)`, async ({ runner }) => {\n const mod = await runner.import('/fixtures/live-binding/test1/index.js')\n expect(mod.default).toMatchInlineSnapshot(`\n [\n 2,\n 3,\n ]\n `)\n })\n\n it(`live binding (export default f)`, async ({ runner }) => {\n const mod = await runner.import('/fixtures/live-binding/test2/index.js')\n expect(mod.default).toMatchInlineSnapshot(`\n [\n 1,\n 1,\n ]\n `)\n })\n\n it(`live binding (export { f as default })`, async ({ runner }) => {\n const mod = await runner.import('/fixtures/live-binding/test3/index.js')\n expect(mod.default).toMatchInlineSnapshot(`\n [\n 2,\n 3,\n ]\n `)\n })\n\n it(`live binding (export default class C)`, async ({ runner }) => {\n const mod = await runner.import('/fixtures/live-binding/test4/index.js')\n expect(mod.default).toMatchInlineSnapshot(`\n [\n 2,\n 3,\n ]\n `)\n })\n\n it(`export default getter is hoisted`, async ({ runner }) => {\n // Node error is `ReferenceError: Cannot access 'dep' before initialization`\n // It should be an error but currently `undefined` fallback.\n expect(\n await runner.import('/fixtures/cyclic2/test9/index.js'),\n ).toMatchInlineSnapshot(\n `\n {\n \"default\": undefined,\n }\n `,\n )\n })\n\n it('oxc runtime helpers are loadable', async ({ runner }) => {\n const mod = await runner.import('/fixtures/oxc-runtime-helper.ts')\n expect(mod.result).toMatchInlineSnapshot(`\n \"\"\n `)\n })\n\n it(`handle Object variable`, async ({ runner }) => {\n const mod = await runner.import('/fixtures/top-level-object.js')\n expect(mod).toMatchInlineSnapshot(`\n {\n \"Object\": \"my-object\",\n }\n `)\n })\n})\n\ndescribe('optimize-deps', async () => {\n const it = await createModuleRunnerTester({\n cacheDir: 'node_modules/.vite-test',\n ssr: {\n noExternal: true,\n optimizeDeps: {\n include: ['@vitejs/cjs-external'],\n },\n },\n })\n\n it('optimized dep as entry', async ({ runner }) => {\n const mod = await runner.import('@vitejs/cjs-external')\n expect(mod.default.hello()).toMatchInlineSnapshot(`\"world\"`)\n })\n})\n\ndescribe('resolveId absolute path entry', async () => {\n const it = await createModuleRunnerTester({\n plugins: [\n {\n name: 'test-resolevId',\n enforce: 'pre',\n resolveId(source) {\n if (\n source ===\n posix.join(this.environment.config.root, 'fixtures/basic.js')\n ) {\n return '\\0virtual:basic'\n }\n },\n load(id) {\n if (id === '\\0virtual:basic') {\n return `export const name = \"virtual:basic\"`\n }\n },\n },\n ],\n })\n\n it('ssrLoadModule', async ({ server }) => {\n const mod = await server.ssrLoadModule(\n posix.join(server.config.root, 'fixtures/basic.js'),\n )\n expect(mod.name).toMatchInlineSnapshot(`\"virtual:basic\"`)\n })\n\n it('runner', async ({ server, runner }) => {\n const mod = await runner.import(\n posix.join(server.config.root, 'fixtures/basic.js'),\n )\n expect(mod.name).toMatchInlineSnapshot(`\"virtual:basic\"`)\n })\n})\n\ndescribe('virtual module hmr', async () => {\n let state = 'init'\n\n const it = await createModuleRunnerTester({\n plugins: [\n {\n name: 'test-resolevId',\n enforce: 'pre',\n resolveId(source) {\n if (source === 'virtual:test') {\n return '\\0' + source\n }\n },\n load(id) {\n if (id === '\\0virtual:test') {\n return `export default ${JSON.stringify(state)}`\n }\n },\n },\n ],\n })\n\n it('full reload', async ({ server, runner }) => {\n const mod = await runner.import('virtual:test')\n expect(mod.default).toBe('init')\n state = 'reloaded'\n server.environments.ssr.moduleGraph.invalidateAll()\n server.environments.ssr.hot.send({ type: 'full-reload' })\n await vi.waitFor(() => {\n const mod = runner.evaluatedModules.getModuleById('\\0virtual:test')\n expect(mod?.exports.default).toBe('reloaded')\n })\n })\n\n it(\"the external module's ID and file are resolved correctly\", async ({\n server,\n runner,\n }) => {\n await runner.import(\n posix.join(server.config.root, 'fixtures/import-external.ts'),\n )\n const moduleNode = runner.evaluatedModules.getModuleByUrl('tinyglobby')!\n const meta = moduleNode.meta as ExternalFetchResult\n if (process.platform === 'win32') {\n expect(meta.externalize).toMatch(/^file:\\/\\/\\/\\w:\\//) // file:///C:/\n expect(moduleNode.id).toMatch(/^\\w:\\//) // C:/\n expect(moduleNode.file).toMatch(/^\\w:\\//) // C:/\n } else {\n expect(meta.externalize).toMatch(/^file:\\/\\/\\//) // file:///\n expect(moduleNode.id).toMatch(/^\\//) // /\n expect(moduleNode.file).toMatch(/^\\//) // /\n }\n })\n})\n\ndescribe('invalid package', async () => {\n const it = await createModuleRunnerTester({\n environments: {\n ssr: {\n resolve: {\n noExternal: true,\n },\n },\n },\n })\n\n it('can catch resolve error on runtime', async ({ runner }) => {\n const mod = await runner.import('./fixtures/invalid-package/test.js')\n expect(await mod.test()).toMatchInlineSnapshot(`\n {\n \"data\": [Error: Failed to resolve entry for package \"test-dep-invalid-exports\". The package may have incorrect main/module/exports specified in its package.json.],\n \"ok\": false,\n }\n `)\n })\n})\n\ndescribe('full-reload during close', () => {\n it('does not error when server closes during full-reload re-import', async () => {\n const errors: (string | Error)[] = []\n const logger: HMRLogger = {\n error: (msg) => errors.push(msg),\n debug: () => {},\n }\n\n const server = await createServer({\n root: import.meta.dirname,\n logLevel: 'error',\n server: {\n middlewareMode: true,\n watch: null,\n ws: false,\n },\n optimizeDeps: {\n disabled: true,\n noDiscovery: true,\n },\n environments: {\n ssr: {\n dev: {\n createEnvironment(name, config) {\n return createRunnableDevEnvironment(name, config, {\n runnerOptions: { hmr: { logger } },\n })\n },\n },\n },\n },\n plugins: [\n {\n name: 'test-slow-virtual',\n enforce: 'pre',\n resolveId(source) {\n if (source === 'virtual:slow') return '\\0virtual:slow'\n },\n async load(id) {\n if (id === '\\0virtual:slow') {\n await setTimeout(10)\n return `export default \"ok\"`\n }\n },\n },\n ],\n })\n\n const env = server.environments.ssr\n if (!isRunnableDevEnvironment(env)) {\n throw new Error('expected RunnableDevEnvironment')\n }\n\n const mod = await env.runner.import('virtual:slow')\n expect(mod.default).toBe('ok')\n\n // re-import will run async via the HMR queue\n env.moduleGraph.invalidateAll()\n env.hot.send({ type: 'full-reload' })\n\n // server.close() -> environment.close() -> runner.close() ->\n // transport.disconnect() rejects the pending fetchModule RPC\n await server.close()\n await setTimeout(100) // Give the HMR handler time to settle\n\n expect(\n errors.some((e) => e.toString().includes('transport was disconnected')),\n ).toBe(false)\n })\n})\n\ndescribe('server.fs check', async () => {\n const it = await createModuleRunnerTester({\n server: {\n fs: {\n allow: [resolve(import.meta.dirname, './fixtures/circular')],\n },\n },\n })\n\n it('it is not applied to the server module runner', async ({ runner }) => {\n const mod = await runner.import('/fixtures/basic.js')\n expect(mod.name).toBe('basic')\n })\n})", "messages": null, "tools": null} {"id": "98b217c63d5e3117", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/shared/forwardConsole.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 6325, "sha256": "888b628540b30ffc94e9ab5802a888abc327b2a7789ff75f9717e2c497dd9af7", "text": "import type { ForwardConsolePayload } from '#types/customEvent'\nimport {\n type NormalizedModuleRunnerTransport,\n SendBeforeConnectError,\n} from './moduleRunnerTransport'\n\nexport type ForwardConsoleLogLevel =\n | 'error'\n | 'warn'\n | 'info'\n | 'log'\n | 'debug'\n | (string & {})\n\nexport interface ForwardConsoleOptions {\n unhandledErrors?: boolean\n logLevels?: ForwardConsoleLogLevel[]\n}\n\nexport interface ResolvedForwardConsoleOptions {\n enabled: boolean\n unhandledErrors: boolean\n logLevels: ForwardConsoleLogLevel[]\n}\n\nexport function setupForwardConsoleHandler(\n transport: NormalizedModuleRunnerTransport,\n options: ResolvedForwardConsoleOptions,\n console: Console = globalThis.console,\n): void {\n if (!options.enabled) {\n return\n }\n\n async function sendError(type: 'error' | 'unhandled-rejection', error: any) {\n await transport.send({\n type: 'custom',\n event: 'vite:forward-console',\n data: {\n type,\n data: {\n name: error?.name || 'Unknown Error',\n message: error?.message || String(error),\n stack: error?.stack,\n },\n } satisfies ForwardConsolePayload,\n })\n }\n\n async function sendLog(level: ForwardConsoleLogLevel, args: unknown[]) {\n try {\n await transport.send({\n type: 'custom',\n event: 'vite:forward-console',\n data: {\n type: 'log',\n data: {\n level,\n message: formatConsoleArgs(args),\n },\n } satisfies ForwardConsolePayload,\n })\n } catch (err) {\n try {\n await sendError('unhandled-rejection', err)\n } catch (err) {\n if (!(err instanceof SendBeforeConnectError)) {\n originalConsoleError('Failed to send error to Vite server:', err)\n }\n }\n }\n }\n\n const originalConsoleError = console.error\n\n for (const level of options.logLevels) {\n const original = (console as any)[level]\n if (typeof original !== 'function') {\n continue\n }\n ;(console as any)[level] = (...args: unknown[]) => {\n original(...args)\n sendLog(level, args)\n }\n }\n\n if (options.unhandledErrors && typeof window !== 'undefined') {\n window.addEventListener('error', async (event) => {\n // `ErrorEvent` doesn't necessarily have `ErrorEvent.error`.\n // Use `ErrorEvent.message` as fallback e.g. for ResizeObserver error.\n // https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent/error\n // https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver#observation_errors\n const error =\n event.error ?? (event.message ? new Error(event.message) : event)\n try {\n await sendError('error', error)\n } catch (err) {\n if (!(err instanceof SendBeforeConnectError)) {\n originalConsoleError('Failed to send error to Vite server:', err)\n }\n }\n })\n\n window.addEventListener('unhandledrejection', async (event) => {\n try {\n await sendError('unhandled-rejection', event.reason)\n } catch (err) {\n if (!(err instanceof SendBeforeConnectError)) {\n originalConsoleError('Failed to send error to Vite server:', err)\n }\n }\n })\n }\n}\n\n// Zero dep version of Vitest's console formatter\n// https://github.com/vitest-dev/vitest/blob/a2d650e00dbd8220397c5c25aef05c850100e446/packages/utils/src/display.ts#L129\nexport function formatConsoleArgs(args: unknown[]): string {\n if (args.length === 0) {\n return ''\n }\n\n if (typeof args[0] !== 'string') {\n return args.map((arg) => stringifyConsoleArg(arg)).join(' ')\n }\n\n const len = args.length\n let i = 1\n let message = args[0].replace(/%[sdjifoOc%]/g, (specifier) => {\n if (specifier === '%%') {\n return '%'\n }\n if (i >= len) {\n return specifier\n }\n\n const arg = args[i++]\n switch (specifier) {\n case '%s':\n if (typeof arg === 'bigint') {\n return `${arg.toString()}n`\n }\n return typeof arg === 'object' && arg != null\n ? stringifyConsoleArg(arg)\n : String(arg)\n case '%d':\n if (typeof arg === 'bigint') {\n return `${arg.toString()}n`\n }\n if (typeof arg === 'symbol') {\n return 'NaN'\n }\n return Number(arg).toString()\n case '%i':\n if (typeof arg === 'bigint') {\n return `${arg.toString()}n`\n }\n return Number.parseInt(String(arg), 10).toString()\n case '%f':\n return Number.parseFloat(String(arg)).toString()\n case '%o':\n case '%O':\n return stringifyConsoleArg(arg)\n case '%j':\n try {\n const serialized = JSON.stringify(arg)\n return serialized ?? 'undefined'\n } catch {\n return '[Circular]'\n }\n case '%c':\n return ''\n default:\n return specifier\n }\n })\n\n for (let arg = args[i]; i < len; arg = args[++i]) {\n if (arg == null || typeof arg !== 'object') {\n message += ` ${typeof arg === 'symbol' ? arg.toString() : String(arg)}`\n } else {\n message += ` ${stringifyConsoleArg(arg)}`\n }\n }\n\n return message\n}\n\nfunction stringifyConsoleArg(value: unknown): string {\n if (typeof value === 'string') {\n return value\n }\n if (\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n typeof value === 'undefined'\n ) {\n return String(value)\n }\n if (typeof value === 'symbol') {\n return value.toString()\n }\n if (typeof value === 'function') {\n return value.name ? `[Function: ${value.name}]` : '[Function]'\n }\n if (value instanceof Error) {\n return value.stack || `${value.name}: ${value.message}`\n }\n if (typeof value === 'bigint') {\n return `${value}n`\n }\n\n const seen = new WeakSet()\n try {\n const serialized = JSON.stringify(value, (_, nested) => {\n if (typeof nested === 'bigint') {\n return `${nested}n`\n }\n if (nested instanceof Error) {\n return {\n name: nested.name,\n message: nested.message,\n stack: nested.stack,\n }\n }\n if (nested && typeof nested === 'object') {\n if (seen.has(nested)) {\n return '[Circular]'\n }\n seen.add(nested)\n }\n return nested\n })\n return serialized ?? String(value)\n } catch {\n return String(value)\n }\n}", "messages": null, "tools": null} {"id": "98c71be8256aeadd", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/node/server/middlewares/error.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 3548, "sha256": "3e0eee00ec3eea26d318111dd4aa674fa921c6c601415bd17b247a410343e900", "text": "import path from 'node:path'\nimport { stripVTControlCharacters as strip } from 'node:util'\nimport colors from 'picocolors'\nimport type { RollupError } from 'rolldown'\nimport type { Connect } from '#dep-types/connect'\nimport type { ErrorPayload } from '#types/hmrPayload'\nimport { pad } from '../../utils'\nimport type { ViteDevServer } from '../..'\nimport { CLIENT_PUBLIC_PATH } from '../../constants'\n\nexport function prepareError(err: Error | RollupError): ErrorPayload['err'] {\n // only copy the information we need and avoid serializing unnecessary\n // properties, since some errors may attach full objects (e.g. PostCSS)\n return {\n message: strip(err.message),\n stack: strip(cleanStack(err.stack || '')),\n id: (err as RollupError).id,\n frame: strip((err as RollupError).frame || ''),\n plugin: (err as RollupError).plugin,\n pluginCode: (err as RollupError).pluginCode?.toString(),\n loc: (err as RollupError).loc,\n }\n}\n\nexport function buildErrorMessage(\n err: RollupError,\n args: string[] = [],\n includeStack = true,\n): string {\n if (err.plugin) args.push(` Plugin: ${colors.magenta(err.plugin)}`)\n const loc = err.loc ? `:${err.loc.line}:${err.loc.column}` : ''\n if (err.id) args.push(` File: ${colors.cyan(err.id)}${loc}`)\n if (err.frame) args.push(colors.yellow(pad(err.frame)))\n if (includeStack && err.stack) args.push(pad(cleanStack(err.stack)))\n return args.join('\\n')\n}\n\nfunction cleanStack(stack: string) {\n return stack\n .split(/\\n/)\n .filter((l) => /^\\s*at/.test(l))\n .join('\\n')\n}\n\nexport function logError(server: ViteDevServer, err: RollupError): void {\n const msg = buildErrorMessage(err, [\n colors.red(`Internal server error: ${err.message}`),\n ])\n\n server.config.logger.error(msg, {\n clear: true,\n timestamp: true,\n error: err,\n })\n\n server.environments.client.hot.send({\n type: 'error',\n err: prepareError(err),\n })\n}\n\nexport function errorMiddleware(\n server: ViteDevServer,\n allowNext = false,\n): Connect.ErrorHandleFunction {\n // note the 4 args must be kept for connect to treat this as error middleware\n // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`\n return function viteErrorMiddleware(err: RollupError, _req, res, next) {\n logError(server, err)\n\n if (allowNext) {\n next()\n } else {\n res.statusCode = 500\n res.end(`\n \n \n \n \n Error\n \n \n \n \n \n `)\n }\n }\n}", "messages": null, "tools": null} {"id": "994528678611fd15", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/worker/self-reference-worker.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 338, "sha256": "604c56d5f1ccb0f09c6fa34305bfd12b8534a16ca8745c7cf97375d81b55f23a", "text": "import SelfWorker from './self-reference-worker?worker'\n\nself.addEventListener('message', (e) => {\n if (e.data === 'main') {\n const selfWorker = new SelfWorker()\n selfWorker.postMessage('nested')\n selfWorker.addEventListener('message', (e) => {\n self.postMessage(e.data)\n })\n }\n\n self.postMessage(`pong: ${e.data}`)\n})", "messages": null, "tools": null} {"id": "9976501ccf0de46f", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/optimize-missing-deps/__test__/optimize-missing-deps.spec.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 475, "sha256": "efcd07c4068ef0bc68ba6ea41e480590cd70beaaf9992e7571fa2f5410281c98", "text": "import { expect, test } from 'vitest'\nimport { port } from './serve'\nimport { isBuild, page } from '~utils'\n\nconst url = `http://localhost:${port}/`\n\ntest.runIf(!isBuild)('optimize', async () => {\n await page.goto(url)\n // reload page to get optimized missing deps\n await page.reload()\n await expect.poll(() => page.textContent('div')).toMatch('Client')\n\n // raw http request\n const aboutHtml = await (await fetch(url)).text()\n expect(aboutHtml).toContain('Server')\n})", "messages": null, "tools": null} {"id": "998e25e7c1bff2ec", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/worker/my-worker.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 821, "sha256": "ad8bdb2bb30d7c268df100be2a159085cac1afcfe61f5e53dc3334886087422a", "text": "import { msg as msgFromDep } from '@vitejs/test-dep-to-optimize'\nimport depCjs from '@vitejs/test-worker-dep-cjs'\nimport { mode, msg } from './modules/workerImport.js'\nimport { bundleWithPlugin } from './modules/test-plugin'\nimport viteSvg from './vite.svg'\nconst metaUrl = import.meta.url\n\nself.onmessage = (e) => {\n if (e.data === 'ping') {\n self.postMessage({\n msg,\n mode,\n bundleWithPlugin,\n viteSvg,\n metaUrl,\n name,\n depCjs,\n })\n }\n if (e.data === 'ping-unicode') {\n self.postMessage({\n msg: '•pong•',\n mode,\n bundleWithPlugin,\n viteSvg,\n metaUrl,\n name,\n depCjs,\n })\n }\n}\nself.postMessage({\n msg,\n mode,\n bundleWithPlugin,\n msgFromDep,\n viteSvg,\n metaUrl,\n name,\n depCjs,\n})\n\n// for sourcemap\nconsole.log('my-worker.js')", "messages": null, "tools": null} {"id": "9a5ed46deab5dde6", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/api/basic_json/insert.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 7471, "sha256": "356452ed64678565a4734b70c7806a4bed11100fa3fc57fb3fec2ed3dfd46850", "text": "# nlohmann::basic_json::insert\n\n```cpp\n// (1)\niterator insert(const_iterator pos, const basic_json& val);\niterator insert(const_iterator pos, basic_json&& val);\n\n// (2)\niterator insert(const_iterator pos, size_type cnt, const basic_json& val);\n\n// (3)\niterator insert(const_iterator pos, const_iterator first, const_iterator last);\n\n// (4)\niterator insert(const_iterator pos, initializer_list_t ilist);\n\n// (5)\nvoid insert(const_iterator first, const_iterator last);\n```\n\n1. Inserts element `val` into an array before iterator `pos`.\n2. Inserts `cnt` copies of `val` into an array before iterator `pos`.\n3. Inserts elements from range `[first, last)` into an array before iterator `pos`.\n4. Inserts elements from initializer list `ilist` into an array before iterator `pos`.\n5. Inserts elements from range `[first, last)` into an object.\n\n## Iterator invalidation\n\nFor all cases where an element is added to an **array**, a reallocation can happen, in which case all iterators\n(including the [`end()`](end.md) iterator) and all references to the elements are invalidated. Otherwise, only the\n[`end()`](end.md) iterator is invalidated. Also, any iterator or reference after the insertion point will point to the\nsame index, which is now a different value.\n\nFor [`ordered_json`](../ordered_json.md), also adding an element to an **object** can yield a reallocation which again\ninvalidates all iterators and all references. Also, any iterator or reference after the insertion point will point to\nthe same index, which is now a different value.\n\n## Parameters\n\n`pos` (in)\n: iterator before which the content will be inserted; may be the `end()` iterator\n\n`val` (in)\n: value to insert\n\n`cnt` (in)\n: number of copies of `val` to insert\n\n`first` (in)\n: the start of the range of elements to insert\n\n`last` (in)\n: the end of the range of elements to insert\n\n`ilist` (in)\n: initializer list to insert the values from\n \n## Return value\n\n1. iterator pointing to the inserted `val`.\n2. iterator pointing to the first element inserted, or `pos` if `#!cpp cnt==0`\n3. iterator pointing to the first element inserted, or `pos` if `#!cpp first==last`\n4. iterator pointing to the first element inserted, or `pos` if `ilist` is empty\n5. (none)\n\n## Exception safety\n\nStrong exception safety: if an exception occurs, the original value stays intact.\n\n## Exceptions\n\n1. The function can throw the following exceptions:\n - Throws [`type_error.309`](../../home/exceptions.md#jsonexceptiontype_error309) if called on JSON values other than\n arrays; example: `\"cannot use insert() with string\"`\n - Throws [`invalid_iterator.202`](../../home/exceptions.md#jsonexceptioninvalid_iterator202) if called on an\n iterator which does not belong to the current JSON value; example: `\"iterator does not fit current value\"`\n2. The function can throw the following exceptions:\n - Throws [`type_error.309`](../../home/exceptions.md#jsonexceptiontype_error309) if called on JSON values other than\n arrays; example: `\"cannot use insert() with string\"`\n - Throws [`invalid_iterator.202`](../../home/exceptions.md#jsonexceptioninvalid_iterator202) if called on an\n iterator which does not belong to the current JSON value; example: `\"iterator does not fit current value\"`\n3. The function can throw the following exceptions:\n - Throws [`type_error.309`](../../home/exceptions.md#jsonexceptiontype_error309) if called on JSON values other than\n arrays; example: `\"cannot use insert() with string\"`\n - Throws [`invalid_iterator.202`](../../home/exceptions.md#jsonexceptioninvalid_iterator202) if called on an\n iterator which does not belong to the current JSON value; example: `\"iterator does not fit current value\"`\n - Throws [`invalid_iterator.210`](../../home/exceptions.md#jsonexceptioninvalid_iterator210) if `first` and `last`\n do not belong to the same JSON value; example: `\"iterators do not fit\"`\n - Throws [`invalid_iterator.211`](../../home/exceptions.md#jsonexceptioninvalid_iterator211) if `first` or `last`\n are iterators into container for which insert is called; example: `\"passed iterators may not belong to container\"`\n4. The function can throw the following exceptions:\n - Throws [`type_error.309`](../../home/exceptions.md#jsonexceptiontype_error309) if called on JSON values other than\n arrays; example: `\"cannot use insert() with string\"`\n - Throws [`invalid_iterator.202`](../../home/exceptions.md#jsonexceptioninvalid_iterator202) if called on an\n iterator which does not belong to the current JSON value; example: `\"iterator does not fit current value\"`\n5. The function can throw the following exceptions:\n - Throws [`type_error.309`](../../home/exceptions.md#jsonexceptiontype_error309) if called on JSON values other than\n objects; example: `\"cannot use insert() with string\"`\n - Throws [`invalid_iterator.202`](../../home/exceptions.md#jsonexceptioninvalid_iterator202) if `first` or `last`\n do not point to an object; example: `\"iterators first and last must point to objects\"`\n - Throws [`invalid_iterator.210`](../../home/exceptions.md#jsonexceptioninvalid_iterator210) if `first` and `last`\n do not belong to the same JSON value; example: `\"iterators do not fit\"`\n\n## Complexity\n\n1. Constant plus linear in the distance between `pos` and end of the container.\n2. Linear in `cnt` plus linear in the distance between `pos` and end of the container.\n3. Linear in `#!cpp std::distance(first, last)` plus linear in the distance between `pos` and end of the container.\n4. Linear in `ilist.size()` plus linear in the distance between `pos` and end of the container.\n5. Logarithmic: `O(N*log(size() + N))`, where `N` is the number of elements to insert.\n\n## Examples\n\n??? example \"Example (1): insert element into array\"\n\n The example shows how `insert()` is used.\n \n ```cpp\n --8<-- \"examples/insert.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/insert.output\"\n ```\n\n??? example \"Example (2): insert copies of element into array\"\n\n The example shows how `insert()` is used.\n \n ```cpp\n --8<-- \"examples/insert__count.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/insert__count.output\"\n ```\n\n??? example \"Example (3): insert a range of elements into an array\"\n\n The example shows how `insert()` is used.\n \n ```cpp\n --8<-- \"examples/insert__range.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/insert__range.output\"\n ```\n\n??? example \"Example (4): insert elements from an initializer list into an array\"\n\n The example shows how `insert()` is used.\n \n ```cpp\n --8<-- \"examples/insert__ilist.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/insert__ilist.output\"\n ```\n\n??? example \"Example (5): insert a range of elements into an object\"\n\n The example shows how `insert()` is used.\n \n ```cpp\n --8<-- \"examples/insert__range_object.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/insert__range_object.output\"\n ```\n\n## See also\n\n- [emplace](emplace.md) add a value to an object\n- [emplace_back](emplace_back.md) add a value to an array\n- [push_back](push_back.md) add a value to an array/object\n- [update](update.md) merges objects\n\n## Version history\n\n1. Added in version 1.0.0.\n2. Added in version 1.0.0.\n3. Added in version 1.0.0.\n4. Added in version 1.0.0.\n5. Added in version 3.0.0.", "messages": null, "tools": null} {"id": "9b321f0bdf11ba58", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/src/fuzzer-parse_bjdata.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 2777, "sha256": "af61067b6adfe20fbd64c39ca8b46552053ca29c7fa665197d45700bb7471884", "text": "// __ _____ _____ _____\n// __| | __| | | | JSON for Modern C++ (supporting code)\n// | | |__ | | | | | | version 3.12.0\n// |_____|_____|_____|_|___| https://github.com/nlohmann/json\n//\n// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann \n// SPDX-License-Identifier: MIT\n\n/*\nThis file implements a parser test suitable for fuzz testing. Given a byte\narray data, it performs the following steps:\n\n- j1 = from_bjdata(data)\n- vec = to_bjdata(j1)\n- j2 = from_bjdata(vec)\n- assert(j1 == j2)\n- vec2 = to_bjdata(j1, use_size = true, use_type = false)\n- j3 = from_bjdata(vec2)\n- assert(j1 == j3)\n- vec3 = to_bjdata(j1, use_size = true, use_type = true)\n- j4 = from_bjdata(vec3)\n- assert(j1 == j4)\n\nThe provided function `LLVMFuzzerTestOneInput` can be used in different fuzzer\ndrivers.\n*/\n\n#include \n#include \n#include \n\nusing json = nlohmann::json;\n\n// see http://llvm.org/docs/LibFuzzer.html\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)\n{\n try\n {\n // step 1: parse input\n std::vector const vec1(data, data + size);\n json const j1 = json::from_bjdata(vec1);\n\n try\n {\n // step 2.1: round trip without adding size annotations to container types\n std::vector const vec2 = json::to_bjdata(j1, false, false);\n\n // step 2.2: round trip with adding size annotations but without adding type annotations to container types\n std::vector const vec3 = json::to_bjdata(j1, true, false);\n\n // step 2.3: round trip with adding size as well as type annotations to container types\n std::vector const vec4 = json::to_bjdata(j1, true, true);\n\n // parse serialization\n json const j2 = json::from_bjdata(vec2);\n json const j3 = json::from_bjdata(vec3);\n json const j4 = json::from_bjdata(vec4);\n\n // serializations must match\n assert(json::to_bjdata(j2, false, false) == vec2);\n assert(json::to_bjdata(j3, true, false) == vec3);\n assert(json::to_bjdata(j4, true, true) == vec4);\n }\n catch (const json::parse_error&)\n {\n // parsing a BJData serialization must not fail\n assert(false);\n }\n }\n catch (const json::parse_error&)\n {\n // parse errors are ok, because input may be random bytes\n }\n catch (const json::type_error&)\n {\n // type errors can occur during parsing, too\n }\n catch (const json::out_of_range&)\n {\n // out of range errors may happen if provided sizes are excessive\n }\n\n // return 0 - non-zero return values are reserved for future use\n return 0;\n}", "messages": null, "tools": null} {"id": "9b3f313c1493da5f", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/src/unit-constructor1.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 57435, "sha256": "91af453a7c26b8ff0a8cd63b685b2d37e765e5ad6ee9147347ae7971da22ef8f", "text": "// __ _____ _____ _____\n// __| | __| | | | JSON for Modern C++ (supporting code)\n// | | |__ | | | | | | version 3.12.0\n// |_____|_____|_____|_|___| https://github.com/nlohmann/json\n//\n// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann \n// SPDX-License-Identifier: MIT\n\n#include \"doctest_compatibility.h\"\n\n#define JSON_TESTS_PRIVATE\n#include \nusing nlohmann::json;\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nTEST_CASE(\"constructors\")\n{\n SECTION(\"create an empty value with a given type\")\n {\n SECTION(\"null\")\n {\n auto const t = json::value_t::null;\n json const j(t);\n CHECK(j.type() == t);\n }\n\n SECTION(\"discarded\")\n {\n auto const t = json::value_t::discarded;\n json const j(t);\n CHECK(j.type() == t);\n }\n\n SECTION(\"object\")\n {\n auto const t = json::value_t::object;\n json const j(t);\n CHECK(j.type() == t);\n }\n\n SECTION(\"array\")\n {\n auto const t = json::value_t::array;\n json const j(t);\n CHECK(j.type() == t);\n }\n\n SECTION(\"boolean\")\n {\n auto const t = json::value_t::boolean;\n json const j(t);\n CHECK(j.type() == t);\n CHECK(j == false);\n }\n\n SECTION(\"string\")\n {\n auto const t = json::value_t::string;\n json const j(t);\n CHECK(j.type() == t);\n CHECK(j == \"\");\n }\n\n SECTION(\"number_integer\")\n {\n auto const t = json::value_t::number_integer;\n json const j(t);\n CHECK(j.type() == t);\n CHECK(j == 0);\n }\n\n SECTION(\"number_unsigned\")\n {\n auto const t = json::value_t::number_unsigned;\n json const j(t);\n CHECK(j.type() == t);\n CHECK(j == 0);\n }\n\n SECTION(\"number_float\")\n {\n auto const t = json::value_t::number_float;\n json const j(t);\n CHECK(j.type() == t);\n CHECK(j == 0.0);\n }\n\n SECTION(\"binary\")\n {\n auto const t = json::value_t::binary;\n json const j(t);\n CHECK(j.type() == t);\n CHECK(j == json::binary({}));\n }\n }\n\n SECTION(\"create a null object (implicitly)\")\n {\n SECTION(\"no parameter\")\n {\n json const j{};\n CHECK(j.type() == json::value_t::null);\n }\n }\n\n SECTION(\"create a null object (explicitly)\")\n {\n SECTION(\"parameter\")\n {\n json const j(nullptr);\n CHECK(j.type() == json::value_t::null);\n }\n }\n\n SECTION(\"create an object (explicit)\")\n {\n SECTION(\"empty object\")\n {\n json::object_t const o{};\n json const j(o);\n CHECK(j.type() == json::value_t::object);\n }\n\n SECTION(\"filled object\")\n {\n json::object_t const o {{\"a\", json(1)}, {\"b\", json(1u)}, {\"c\", json(2.2)}, {\"d\", json(false)}, {\"e\", json(\"string\")}, {\"f\", json()}};\n json const j(o);\n CHECK(j.type() == json::value_t::object);\n }\n }\n\n SECTION(\"create an object (implicit)\")\n {\n // reference object\n json::object_t const o_reference {{\"a\", json(1)}, {\"b\", json(1u)}, {\"c\", json(2.2)}, {\"d\", json(false)}, {\"e\", json(\"string\")}, {\"f\", json()}};\n json const j_reference(o_reference);\n\n SECTION(\"std::map\")\n {\n std::map const o {{\"a\", json(1)}, {\"b\", json(1u)}, {\"c\", json(2.2)}, {\"d\", json(false)}, {\"e\", json(\"string\")}, {\"f\", json()}};\n json const j(o);\n CHECK(j.type() == json::value_t::object);\n CHECK(j == j_reference);\n }\n\n SECTION(\"std::map #600\")\n {\n const std::map m\n {\n {\"a\", \"b\"},\n {\"c\", \"d\"},\n {\"e\", \"f\"},\n };\n\n json const j(m);\n CHECK((j.get() == m));\n }\n\n SECTION(\"std::map\")\n {\n std::map const o {{\"a\", json(1)}, {\"b\", json(1u)}, {\"c\", json(2.2)}, {\"d\", json(false)}, {\"e\", json(\"string\")}, {\"f\", json()}};\n json const j(o);\n CHECK(j.type() == json::value_t::object);\n CHECK(j == j_reference);\n }\n\n SECTION(\"std::multimap\")\n {\n std::multimap const o {{\"a\", json(1)}, {\"b\", json(1u)}, {\"c\", json(2.2)}, {\"d\", json(false)}, {\"e\", json(\"string\")}, {\"f\", json()}};\n json const j(o);\n CHECK(j.type() == json::value_t::object);\n CHECK(j == j_reference);\n }\n\n SECTION(\"std::unordered_map\")\n {\n std::unordered_map const o {{\"a\", json(1)}, {\"b\", json(1u)}, {\"c\", json(2.2)}, {\"d\", json(false)}, {\"e\", json(\"string\")}, {\"f\", json()}};\n json const j(o);\n CHECK(j.type() == json::value_t::object);\n CHECK(j == j_reference);\n }\n\n SECTION(\"std::unordered_multimap\")\n {\n std::unordered_multimap const o {{\"a\", json(1)}, {\"b\", json(1u)}, {\"c\", json(2.2)}, {\"d\", json(false)}, {\"e\", json(\"string\")}, {\"f\", json()}};\n json const j(o);\n CHECK(j.type() == json::value_t::object);\n CHECK(j == j_reference);\n }\n\n SECTION(\"associative container literal\")\n {\n json const j({{\"a\", json(1)}, {\"b\", json(1u)}, {\"c\", json(2.2)}, {\"d\", json(false)}, {\"e\", json(\"string\")}, {\"f\", json()}});\n CHECK(j.type() == json::value_t::object);\n CHECK(j == j_reference);\n }\n }\n\n SECTION(\"create an array (explicit)\")\n {\n SECTION(\"empty array\")\n {\n json::array_t const a{};\n json const j(a);\n CHECK(j.type() == json::value_t::array);\n }\n\n SECTION(\"filled array\")\n {\n json::array_t const a {json(1), json(1u), json(2.2), json(false), json(\"string\"), json()};\n json const j(a);\n CHECK(j.type() == json::value_t::array);\n }\n }\n\n SECTION(\"create an array (implicit)\")\n {\n // reference array\n json::array_t const a_reference {json(1), json(1u), json(2.2), json(false), json(\"string\"), json()};\n json const j_reference(a_reference);\n\n SECTION(\"std::list\")\n {\n std::list const a {json(1), json(1u), json(2.2), json(false), json(\"string\"), json()};\n json const j(a);\n CHECK(j.type() == json::value_t::array);\n CHECK(j == j_reference);\n }\n\n SECTION(\"std::pair\")\n {\n std::pair const p{1.0f, \"string\"};\n json const j(p);\n\n CHECK(j.type() == json::value_t::array);\n CHECK(j.get() == p);\n REQUIRE(j.size() == 2);\n CHECK(j[0] == std::get<0>(p));\n CHECK(j[1] == std::get<1>(p));\n }\n\n SECTION(\"std::pair with discarded values\")\n {\n json const j{1, 2.0, \"string\"};\n\n const auto p = j.get>();\n CHECK(p.first == j[0]);\n CHECK(p.second == j[1]);\n }\n\n SECTION(\"std::tuple\")\n {\n const auto t = std::make_tuple(1.0, std::string{\"string\"}, 42, std::vector {0, 1});\n json const j(t);\n\n CHECK(j.type() == json::value_t::array);\n REQUIRE(j.size() == 4);\n CHECK(j.get() == t);\n CHECK(j[0] == std::get<0>(t));\n CHECK(j[1] == std::get<1>(t));\n CHECK(j[2] == std::get<2>(t));\n CHECK(j[3][0] == 0);\n CHECK(j[3][1] == 1);\n }\n\n SECTION(\"std::tuple with discarded values\")\n {\n json const j{1, 2.0, \"string\", 42};\n\n const auto t = j.get>();\n CHECK(std::get<0>(t) == j[0]);\n CHECK(std::get<1>(t) == j[1]);\n CHECK(std::get<2>(t) == j[2]);\n }\n\n SECTION(\"std::tuple tie\")\n {\n const auto a = 1.0;\n const auto* const b = \"string\";\n const auto c = 42;\n const auto d = std::vector {0, 2};\n const size_t e = 1234;\n auto t = std::tie(a, b, c, d, e);\n json const j(t);\n\n double a_out = 0;\n std::string b_out;\n int c_out = 0;\n std::vector d_out;\n int64_t e_out = 0;\n auto t_out = std::tie(a_out, b_out, c_out, d_out, e_out);\n j.get_to(t_out);\n CHECK(a_out == a);\n CHECK(b_out == b);\n CHECK(c_out == c);\n CHECK(d_out == d);\n CHECK(e_out == e);\n }\n\n SECTION(\"std::tuple of references to elements\")\n {\n const auto a = 1.0;\n const auto* const b = \"string\";\n const auto c = 42;\n const size_t d = 1234;\n const auto t = std::tie(a, b, c, d);\n json const j(t);\n\n auto t_out = j.get>();\n CHECK(&std::get<0>(t_out) == j[0].get_ptr());\n CHECK(&std::get<1>(t_out) == j[1].get_ptr());\n CHECK(&std::get<2>(t_out) == j[2].get_ptr());\n CHECK(&std::get<3>(t_out) == j[3].get_ptr());\n CHECK(std::get<0>(t_out) == a);\n CHECK(std::get<1>(t_out) == b);\n CHECK(std::get<2>(t_out) == c);\n CHECK(std::get<3>(t_out) == d);\n }\n\n SECTION(\"std::tuple mixed arithmetic types\")\n {\n using j_float_t = json::number_float_t;\n using j_int_t = json::number_integer_t;\n using j_uint_t = json::number_unsigned_t;\n const j_float_t a = 1.0;\n const j_int_t b = 1234;\n const j_uint_t c = 42;\n json const j(std::tie(a, b, c, c));\n\n auto t1 = j.get>();\n j_uint_t a2 = 0;\n j_float_t b2 = 0;\n j_int_t c2 = 0;\n auto t2 = std::tie(a2, b2, c2);\n j.get_to(t2);\n\n CHECK(std::get<0>(t1) == static_cast(a));\n CHECK(std::get<1>(t1) == static_cast(b));\n CHECK(std::get<2>(t1) == static_cast(c));\n // t1[3] exists only to force usage of the no-default-constructor version\n CHECK(a2 == static_cast(a));\n CHECK(b2 == static_cast(b));\n CHECK(c2 == static_cast(c));\n }\n\n SECTION(\"std::pair/tuple/array failures\")\n {\n json const j{1};\n\n CHECK_THROWS_WITH_AS((j.get>()), \"[json.exception.out_of_range.401] array index 1 is out of range\", json::out_of_range&);\n CHECK_THROWS_WITH_AS((j.get>()), \"[json.exception.out_of_range.401] array index 1 is out of range\", json::out_of_range&);\n CHECK_THROWS_WITH_AS((j.get>()), \"[json.exception.out_of_range.401] array index 1 is out of range\", json::out_of_range&);\n }\n\n SECTION(\"std::forward_list\")\n {\n std::forward_list const a {json(1), json(1u), json(2.2), json(false), json(\"string\"), json()};\n json const j(a);\n CHECK(j.type() == json::value_t::array);\n CHECK(j == j_reference);\n }\n\n SECTION(\"std::array\")\n {\n std::array const a {{json(1), json(1u), json(2.2), json(false), json(\"string\"), json()}};\n json const j(a);\n CHECK(j.type() == json::value_t::array);\n CHECK(j == j_reference);\n\n const auto a2 = j.get>();\n CHECK(a2 == a);\n }\n\n SECTION(\"std::valarray\")\n {\n std::valarray const va = {1, 2, 3, 4, 5};\n json const j(va);\n CHECK(j.type() == json::value_t::array);\n CHECK(j == json({1, 2, 3, 4, 5}));\n\n auto jva = j.get>();\n CHECK(jva.size() == va.size());\n for (size_t i = 0; i < jva.size(); ++i)\n {\n CHECK(va[i] == jva[i]);\n }\n }\n\n SECTION(\"std::valarray\")\n {\n std::valarray const va = {1.2, 2.3, 3.4, 4.5, 5.6};\n json const j(va);\n CHECK(j.type() == json::value_t::array);\n CHECK(j == json({1.2, 2.3, 3.4, 4.5, 5.6}));\n\n auto jva = j.get>();\n CHECK(jva.size() == va.size());\n for (size_t i = 0; i < jva.size(); ++i)\n {\n CHECK(va[i] == jva[i]);\n }\n }\n\n SECTION(\"std::vector\")\n {\n std::vector const a {json(1), json(1u), json(2.2), json(false), json(\"string\"), json()};\n json const j(a);\n CHECK(j.type() == json::value_t::array);\n CHECK(j == j_reference);\n }\n\n SECTION(\"std::deque\")\n {\n std::deque const a {json(1), json(1u), json(2.2), json(false), json(\"string\"), json()};\n json const j(a);\n CHECK(j.type() == json::value_t::array);\n CHECK(j == j_reference);\n }\n\n SECTION(\"std::set\")\n {\n std::set const a {json(1), json(1u), json(2.2), json(false), json(\"string\"), json()};\n json const j(a);\n CHECK(j.type() == json::value_t::array);\n // we cannot really check for equality here\n }\n\n SECTION(\"std::unordered_set\")\n {\n std::unordered_set const a {json(1), json(1u), json(2.2), json(false), json(\"string\"), json()};\n json const j(a);\n CHECK(j.type() == json::value_t::array);\n // we cannot really check for equality here\n }\n\n SECTION(\"sequence container literal\")\n {\n json const j({json(1), json(1u), json(2.2), json(false), json(\"string\"), json()});\n CHECK(j.type() == json::value_t::array);\n CHECK(j == j_reference);\n }\n }\n\n SECTION(\"create a string (explicit)\")\n {\n SECTION(\"empty string\")\n {\n json::string_t const s{};\n json const j(s);\n CHECK(j.type() == json::value_t::string);\n }\n\n SECTION(\"filled string\")\n {\n json::string_t const s {\"Hello world\"};\n json const j(s);\n CHECK(j.type() == json::value_t::string);\n }\n }\n\n SECTION(\"create a string (implicit)\")\n {\n // reference string\n json::string_t const s_reference {\"Hello world\"};\n json const j_reference(s_reference);\n\n SECTION(\"std::string\")\n {\n std::string const s {\"Hello world\"};\n json const j(s);\n CHECK(j.type() == json::value_t::string);\n CHECK(j == j_reference);\n }\n\n SECTION(\"char[]\")\n {\n const char s[] {\"Hello world\"}; // NOLINT(misc-const-correctness,cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)\n json const j(s);\n CHECK(j.type() == json::value_t::string);\n CHECK(j == j_reference);\n }\n\n SECTION(\"const char*\")\n {\n const char* s {\"Hello world\"};\n json const j(s);\n CHECK(j.type() == json::value_t::string);\n CHECK(j == j_reference);\n }\n\n SECTION(\"string literal\")\n {\n json const j(\"Hello world\");\n CHECK(j.type() == json::value_t::string);\n CHECK(j == j_reference);\n }\n }\n\n SECTION(\"create a boolean (explicit)\")\n {\n SECTION(\"empty boolean\")\n {\n json::boolean_t const b{};\n json const j(b);\n CHECK(j.type() == json::value_t::boolean);\n }\n\n SECTION(\"filled boolean (true)\")\n {\n json const j(true);\n CHECK(j.type() == json::value_t::boolean);\n }\n\n SECTION(\"filled boolean (false)\")\n {\n json const j(false);\n CHECK(j.type() == json::value_t::boolean);\n }\n\n SECTION(\"from std::vector::reference\")\n {\n std::vector v{true};\n json const j(v[0]);\n CHECK(std::is_same::reference>::value);\n CHECK(j.type() == json::value_t::boolean);\n }\n\n SECTION(\"from std::vector::const_reference\")\n {\n const std::vector v{true};\n json const j(v[0]);\n CHECK(std::is_same::const_reference>::value);\n CHECK(j.type() == json::value_t::boolean);\n }\n }\n\n SECTION(\"create a binary (explicit)\")\n {\n SECTION(\"empty binary\")\n {\n json::binary_t const b{};\n json const j(b);\n CHECK(j.type() == json::value_t::binary);\n }\n\n SECTION(\"filled binary\")\n {\n json::binary_t const b({1, 2, 3});\n json const j(b);\n CHECK(j.type() == json::value_t::binary);\n }\n }\n\n SECTION(\"create an integer number (explicit)\")\n {\n SECTION(\"uninitialized value\")\n {\n json::number_integer_t const n{};\n json const j(n);\n CHECK(j.type() == json::value_t::number_integer);\n }\n\n SECTION(\"initialized value\")\n {\n json::number_integer_t const n(42);\n json const j(n);\n CHECK(j.type() == json::value_t::number_integer);\n }\n }\n\n SECTION(\"create an integer number (implicit)\")\n {\n // reference objects\n json::number_integer_t const n_reference = 42;\n json const j_reference(n_reference);\n json::number_unsigned_t const n_unsigned_reference = 42;\n json const j_unsigned_reference(n_unsigned_reference);\n\n SECTION(\"short\")\n {\n short const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_integer);\n CHECK(j == j_reference);\n }\n\n SECTION(\"unsigned short\")\n {\n unsigned short const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_unsigned);\n CHECK(j == j_unsigned_reference);\n }\n\n SECTION(\"int\")\n {\n int const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_integer);\n CHECK(j == j_reference);\n }\n\n SECTION(\"unsigned int\")\n {\n unsigned int const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_unsigned);\n CHECK(j == j_unsigned_reference);\n }\n\n SECTION(\"long\")\n {\n long const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_integer);\n CHECK(j == j_reference);\n }\n\n SECTION(\"unsigned long\")\n {\n unsigned long const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_unsigned);\n CHECK(j == j_unsigned_reference);\n }\n\n SECTION(\"long long\")\n {\n long long const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_integer);\n CHECK(j == j_reference);\n }\n\n SECTION(\"unsigned long long\")\n {\n unsigned long long const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_unsigned);\n CHECK(j == j_unsigned_reference);\n }\n\n SECTION(\"int8_t\")\n {\n int8_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_integer);\n CHECK(j == j_reference);\n }\n\n SECTION(\"int16_t\")\n {\n int16_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_integer);\n CHECK(j == j_reference);\n }\n\n SECTION(\"int32_t\")\n {\n int32_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_integer);\n CHECK(j == j_reference);\n }\n\n SECTION(\"int64_t\")\n {\n int64_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_integer);\n CHECK(j == j_reference);\n }\n\n SECTION(\"int_fast8_t\")\n {\n int_fast8_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_integer);\n CHECK(j == j_reference);\n }\n\n SECTION(\"int_fast16_t\")\n {\n int_fast16_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_integer);\n CHECK(j == j_reference);\n }\n\n SECTION(\"int_fast32_t\")\n {\n int_fast32_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_integer);\n CHECK(j == j_reference);\n }\n\n SECTION(\"int_fast64_t\")\n {\n int_fast64_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_integer);\n CHECK(j == j_reference);\n }\n\n SECTION(\"int_least8_t\")\n {\n int_least8_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_integer);\n CHECK(j == j_reference);\n }\n\n SECTION(\"int_least16_t\")\n {\n int_least16_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_integer);\n CHECK(j == j_reference);\n }\n\n SECTION(\"int_least32_t\")\n {\n int_least32_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_integer);\n CHECK(j == j_reference);\n }\n\n SECTION(\"int_least64_t\")\n {\n int_least64_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_integer);\n CHECK(j == j_reference);\n }\n\n SECTION(\"uint8_t\")\n {\n uint8_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_unsigned);\n CHECK(j == j_unsigned_reference);\n }\n\n SECTION(\"uint16_t\")\n {\n uint16_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_unsigned);\n CHECK(j == j_unsigned_reference);\n }\n\n SECTION(\"uint32_t\")\n {\n uint32_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_unsigned);\n CHECK(j == j_unsigned_reference);\n }\n\n SECTION(\"uint64_t\")\n {\n uint64_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_unsigned);\n CHECK(j == j_unsigned_reference);\n }\n\n SECTION(\"uint_fast8_t\")\n {\n uint_fast8_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_unsigned);\n CHECK(j == j_unsigned_reference);\n }\n\n SECTION(\"uint_fast16_t\")\n {\n uint_fast16_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_unsigned);\n CHECK(j == j_unsigned_reference);\n }\n\n SECTION(\"uint_fast32_t\")\n {\n uint_fast32_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_unsigned);\n CHECK(j == j_unsigned_reference);\n }\n\n SECTION(\"uint_fast64_t\")\n {\n uint_fast64_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_unsigned);\n CHECK(j == j_unsigned_reference);\n }\n\n SECTION(\"uint_least8_t\")\n {\n uint_least8_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_unsigned);\n CHECK(j == j_unsigned_reference);\n }\n\n SECTION(\"uint_least16_t\")\n {\n uint_least16_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_unsigned);\n CHECK(j == j_unsigned_reference);\n }\n\n SECTION(\"uint_least32_t\")\n {\n uint_least32_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_unsigned);\n CHECK(j == j_unsigned_reference);\n }\n\n SECTION(\"uint_least64_t\")\n {\n uint_least64_t const n = 42;\n json const j(n);\n CHECK(j.type() == json::value_t::number_unsigned);\n CHECK(j == j_unsigned_reference);\n }\n\n SECTION(\"integer literal without suffix\")\n {\n json const j(42);\n CHECK(j.type() == json::value_t::number_integer);\n CHECK(j == j_reference);\n }\n\n SECTION(\"integer literal with u suffix\")\n {\n const json j(42u);\n CHECK(j.type() == json::value_t::number_unsigned);\n CHECK(j == j_unsigned_reference);\n }\n\n SECTION(\"integer literal with l suffix\")\n {\n json const j(42L);\n CHECK(j.type() == json::value_t::number_integer);\n CHECK(j == j_reference);\n }\n\n SECTION(\"integer literal with ul suffix\")\n {\n const json j(42ul);\n CHECK(j.type() == json::value_t::number_unsigned);\n CHECK(j == j_unsigned_reference);\n }\n\n SECTION(\"integer literal with ll suffix\")\n {\n json const j(42LL);\n CHECK(j.type() == json::value_t::number_integer);\n CHECK(j == j_reference);\n }\n\n SECTION(\"integer literal with ull suffix\")\n {\n const json j(42ull);\n CHECK(j.type() == json::value_t::number_unsigned);\n CHECK(j == j_unsigned_reference);\n }\n }\n\n SECTION(\"create a floating-point number (explicit)\")\n {\n SECTION(\"uninitialized value\")\n {\n json::number_float_t const n{};\n json const j(n);\n CHECK(j.type() == json::value_t::number_float);\n }\n\n SECTION(\"initialized value\")\n {\n json::number_float_t const n(42.23);\n json const j(n);\n CHECK(j.type() == json::value_t::number_float);\n }\n\n SECTION(\"NaN\")\n {\n // NaN is stored properly, but serialized to null\n json::number_float_t const n(std::numeric_limits::quiet_NaN());\n json const j(n);\n CHECK(j.type() == json::value_t::number_float);\n\n // check round trip of NaN\n json::number_float_t const d{j};\n CHECK((std::isnan(d) && std::isnan(n)) == true);\n\n // check that NaN is serialized to null\n CHECK(j.dump() == \"null\");\n }\n\n SECTION(\"infinity\")\n {\n // infinity is stored properly, but serialized to null\n json::number_float_t const n(std::numeric_limits::infinity());\n json const j(n);\n CHECK(j.type() == json::value_t::number_float);\n\n // check round trip of infinity\n json::number_float_t const d{j};\n CHECK(d == n);\n\n // check that inf is serialized to null\n CHECK(j.dump() == \"null\");\n }\n }\n\n SECTION(\"create a floating-point number (implicit)\")\n {\n // reference object\n json::number_float_t const n_reference = 42.23;\n json const j_reference(n_reference);\n\n SECTION(\"float\")\n {\n float const n = 42.23f;\n json const j(n);\n CHECK(j.type() == json::value_t::number_float);\n CHECK(j.m_data.m_value.number_float == Approx(j_reference.m_data.m_value.number_float));\n }\n\n SECTION(\"double\")\n {\n double const n = 42.23;\n json const j(n);\n CHECK(j.type() == json::value_t::number_float);\n CHECK(j.m_data.m_value.number_float == Approx(j_reference.m_data.m_value.number_float));\n }\n\n SECTION(\"long double\")\n {\n long double const n = 42.23L;\n json const j(n);\n CHECK(j.type() == json::value_t::number_float);\n CHECK(j.m_data.m_value.number_float == Approx(j_reference.m_data.m_value.number_float));\n }\n\n SECTION(\"floating-point literal without suffix\")\n {\n json const j(42.23);\n CHECK(j.type() == json::value_t::number_float);\n CHECK(j.m_data.m_value.number_float == Approx(j_reference.m_data.m_value.number_float));\n }\n\n SECTION(\"integer literal with f suffix\")\n {\n json const j(42.23f);\n CHECK(j.type() == json::value_t::number_float);\n CHECK(j.m_data.m_value.number_float == Approx(j_reference.m_data.m_value.number_float));\n }\n\n SECTION(\"integer literal with l suffix\")\n {\n json const j(42.23L);\n CHECK(j.type() == json::value_t::number_float);\n CHECK(j.m_data.m_value.number_float == Approx(j_reference.m_data.m_value.number_float));\n }\n }\n\n SECTION(\"create a container (array or object) from an initializer list\")\n {\n SECTION(\"empty initializer list\")\n {\n SECTION(\"explicit\")\n {\n json const j(json::initializer_list_t {});\n CHECK(j.type() == json::value_t::object);\n }\n\n SECTION(\"implicit\")\n {\n json const j {};\n CHECK(j.type() == json::value_t::null);\n }\n }\n\n SECTION(\"one element\")\n {\n SECTION(\"array\")\n {\n SECTION(\"explicit\")\n {\n json const j(json::initializer_list_t {json(json::array_t())});\n CHECK(j.type() == json::value_t::array);\n }\n\n SECTION(\"implicit\")\n {\n json const j {json::array_t()};\n CHECK(j.type() == json::value_t::array);\n }\n }\n\n SECTION(\"object\")\n {\n SECTION(\"explicit\")\n {\n json const j(json::initializer_list_t {json(json::object_t())});\n CHECK(j.type() == json::value_t::array);\n }\n\n SECTION(\"implicit\")\n {\n json const j {json::object_t()};\n CHECK(j.type() == json::value_t::array);\n }\n }\n\n SECTION(\"string\")\n {\n SECTION(\"explicit\")\n {\n json const j(json::initializer_list_t {json(\"Hello world\")});\n CHECK(j.type() == json::value_t::array);\n }\n\n SECTION(\"implicit\")\n {\n json const j {\"Hello world\"};\n CHECK(j.type() == json::value_t::array);\n }\n }\n\n SECTION(\"boolean\")\n {\n SECTION(\"explicit\")\n {\n json const j(json::initializer_list_t {json(true)});\n CHECK(j.type() == json::value_t::array);\n }\n\n SECTION(\"implicit\")\n {\n json const j {true};\n CHECK(j.type() == json::value_t::array);\n }\n }\n\n SECTION(\"number (integer)\")\n {\n SECTION(\"explicit\")\n {\n json const j(json::initializer_list_t {json(1)});\n CHECK(j.type() == json::value_t::array);\n }\n\n SECTION(\"implicit\")\n {\n json const j {1};\n CHECK(j.type() == json::value_t::array);\n }\n }\n\n SECTION(\"number (unsigned)\")\n {\n SECTION(\"explicit\")\n {\n json const j(json::initializer_list_t {json(1u)});\n CHECK(j.type() == json::value_t::array);\n }\n\n SECTION(\"implicit\")\n {\n json const j {1u};\n CHECK(j.type() == json::value_t::array);\n }\n }\n\n SECTION(\"number (floating-point)\")\n {\n SECTION(\"explicit\")\n {\n json const j(json::initializer_list_t {json(42.23)});\n CHECK(j.type() == json::value_t::array);\n }\n\n SECTION(\"implicit\")\n {\n json const j {42.23};\n CHECK(j.type() == json::value_t::array);\n }\n }\n }\n\n SECTION(\"more elements\")\n {\n SECTION(\"explicit\")\n {\n json const j(json::initializer_list_t {1, 1u, 42.23, true, nullptr, json::object_t(), json::array_t()});\n CHECK(j.type() == json::value_t::array);\n }\n\n SECTION(\"implicit\")\n {\n json const j {1, 1u, 42.23, true, nullptr, json::object_t(), json::array_t()};\n CHECK(j.type() == json::value_t::array);\n }\n }\n\n SECTION(\"implicit type deduction\")\n {\n SECTION(\"object\")\n {\n json const j { {\"one\", 1}, {\"two\", 1u}, {\"three\", 2.2}, {\"four\", false} };\n CHECK(j.type() == json::value_t::object);\n }\n\n SECTION(\"array\")\n {\n json const j { {\"one\", 1}, {\"two\", 1u}, {\"three\", 2.2}, {\"four\", false}, 13 };\n CHECK(j.type() == json::value_t::array);\n }\n }\n\n SECTION(\"explicit type deduction\")\n {\n SECTION(\"empty object\")\n {\n json const j = json::object();\n CHECK(j.type() == json::value_t::object);\n }\n\n SECTION(\"object\")\n {\n json const j = json::object({ {\"one\", 1}, {\"two\", 1u}, {\"three\", 2.2}, {\"four\", false} });\n CHECK(j.type() == json::value_t::object);\n }\n\n SECTION(\"object with error\")\n {\n json _;\n CHECK_THROWS_WITH_AS(_ = json::object({ {\"one\", 1}, {\"two\", 1u}, {\"three\", 2.2}, {\"four\", false}, 13 }), \"[json.exception.type_error.301] cannot create object from initializer list\", json::type_error&);\n }\n\n SECTION(\"empty array\")\n {\n json const j = json::array();\n CHECK(j.type() == json::value_t::array);\n }\n\n SECTION(\"array\")\n {\n json const j = json::array({ {\"one\", 1}, {\"two\", 1u}, {\"three\", 2.2}, {\"four\", false} });\n CHECK(j.type() == json::value_t::array);\n }\n }\n\n SECTION(\"move from initializer_list\")\n {\n SECTION(\"string\")\n {\n SECTION(\"constructor with implicit types (array)\")\n {\n // This should break through any short string optimization in std::string\n std::string source(1024, '!');\n const auto* source_addr = source.data();\n json j = {std::move(source)};\n const auto* target_addr = j[0].get_ref().data();\n const bool success = (target_addr == source_addr);\n CHECK(success);\n }\n\n SECTION(\"constructor with implicit types (object)\")\n {\n // This should break through any short string optimization in std::string\n std::string source(1024, '!');\n const auto* source_addr = source.data();\n json j = {{\"key\", std::move(source)}};\n const auto* target_addr = j[\"key\"].get_ref().data();\n const bool success = (target_addr == source_addr);\n CHECK(success);\n }\n\n SECTION(\"constructor with implicit types (object key)\")\n {\n // This should break through any short string optimization in std::string\n std::string source(1024, '!');\n const auto* source_addr = source.data();\n json j = {{std::move(source), 42}};\n const auto* target_addr = j.get_ref().begin()->first.data();\n const bool success = (target_addr == source_addr);\n CHECK(success);\n }\n }\n\n SECTION(\"array\")\n {\n SECTION(\"constructor with implicit types (array)\")\n {\n json::array_t source = {1, 2, 3};\n const auto* source_addr = source.data();\n json j {std::move(source)};\n const auto* target_addr = j[0].get_ref().data();\n const bool success = (target_addr == source_addr);\n CHECK(success);\n }\n\n SECTION(\"constructor with implicit types (object)\")\n {\n json::array_t source = {1, 2, 3};\n const auto* source_addr = source.data();\n json const j {{\"key\", std::move(source)}};\n const auto* target_addr = j[\"key\"].get_ref().data();\n const bool success = (target_addr == source_addr);\n CHECK(success);\n }\n\n SECTION(\"assignment with implicit types (array)\")\n {\n json::array_t source = {1, 2, 3};\n const auto* source_addr = source.data();\n json j = {std::move(source)};\n const auto* target_addr = j[0].get_ref().data();\n const bool success = (target_addr == source_addr);\n CHECK(success);\n }\n\n SECTION(\"assignment with implicit types (object)\")\n {\n json::array_t source = {1, 2, 3};\n const auto* source_addr = source.data();\n json j = {{\"key\", std::move(source)}};\n const auto* target_addr = j[\"key\"].get_ref().data();\n const bool success = (target_addr == source_addr);\n CHECK(success);\n }\n }\n\n SECTION(\"object\")\n {\n SECTION(\"constructor with implicit types (array)\")\n {\n json::object_t source = {{\"hello\", \"world\"}};\n const json* source_addr = &source.at(\"hello\");\n json j {std::move(source)};\n CHECK(&(j[0].get_ref().at(\"hello\")) == source_addr);\n }\n\n SECTION(\"constructor with implicit types (object)\")\n {\n json::object_t source = {{\"hello\", \"world\"}};\n const json* source_addr = &source.at(\"hello\");\n json j {{\"key\", std::move(source)}};\n CHECK(&(j[\"key\"].get_ref().at(\"hello\")) == source_addr);\n }\n\n SECTION(\"assignment with implicit types (array)\")\n {\n json::object_t source = {{\"hello\", \"world\"}};\n const json* source_addr = &source.at(\"hello\");\n json j = {std::move(source)};\n CHECK(&(j[0].get_ref().at(\"hello\")) == source_addr);\n }\n\n SECTION(\"assignment with implicit types (object)\")\n {\n json::object_t source = {{\"hello\", \"world\"}};\n const json* source_addr = &source.at(\"hello\");\n json j = {{\"key\", std::move(source)}};\n CHECK(&(j[\"key\"].get_ref().at(\"hello\")) == source_addr);\n }\n }\n\n SECTION(\"json\")\n {\n SECTION(\"constructor with implicit types (array)\")\n {\n json source {1, 2, 3};\n const json* source_addr = &source[0];\n json j {std::move(source), {}};\n CHECK(&j[0][0] == source_addr);\n }\n\n SECTION(\"constructor with implicit types (object)\")\n {\n json source {1, 2, 3};\n const json* source_addr = &source[0];\n json j {{\"key\", std::move(source)}};\n CHECK(&j[\"key\"][0] == source_addr);\n }\n\n SECTION(\"assignment with implicit types (array)\")\n {\n json source {1, 2, 3};\n const json* source_addr = &source[0];\n json j = {std::move(source), {}};\n CHECK(&j[0][0] == source_addr);\n }\n\n SECTION(\"assignment with implicit types (object)\")\n {\n json source {1, 2, 3};\n const json* source_addr = &source[0];\n json j = {{\"key\", std::move(source)}};\n CHECK(&j[\"key\"][0] == source_addr);\n }\n }\n\n }\n }\n\n SECTION(\"create an array of n copies of a given value\")\n {\n SECTION(\"cnt = 0\")\n {\n json const v = {1, \"foo\", 34.23, {1, 2, 3}, {{\"A\", 1}, {\"B\", 2u}}};\n json const arr(0, v);\n CHECK(arr.size() == 0);\n }\n\n SECTION(\"cnt = 1\")\n {\n json const v = {1, \"foo\", 34.23, {1, 2, 3}, {{\"A\", 1}, {\"B\", 2u}}};\n json const arr(1, v);\n CHECK(arr.size() == 1);\n for (const auto& x : arr)\n {\n CHECK(x == v);\n }\n }\n\n SECTION(\"cnt = 3\")\n {\n json const v = {1, \"foo\", 34.23, {1, 2, 3}, {{\"A\", 1}, {\"B\", 2u}}};\n json const arr(3, v);\n CHECK(arr.size() == 3);\n for (const auto& x : arr)\n {\n CHECK(x == v);\n }\n }\n }\n\n SECTION(\"create a JSON container from an iterator range\")\n {\n SECTION(\"object\")\n {\n SECTION(\"json(begin(), end())\")\n {\n {\n json jobject = {{\"a\", \"a\"}, {\"b\", 1}, {\"c\", 17u}};\n json const j_new(jobject.begin(), jobject.end());\n CHECK(j_new == jobject);\n }\n {\n json jobject = {{\"a\", \"a\"}, {\"b\", 1}, {\"c\", 17u}};\n json const j_new(jobject.cbegin(), jobject.cend());\n CHECK(j_new == jobject);\n }\n }\n\n SECTION(\"json(begin(), begin())\")\n {\n {\n json jobject = {{\"a\", \"a\"}, {\"b\", 1}, {\"c\", 17u}};\n json const j_new(jobject.begin(), jobject.begin());\n CHECK(j_new == json::object());\n }\n {\n json const jobject = {{\"a\", \"a\"}, {\"b\", 1}, {\"c\", 17u}};\n json const j_new(jobject.cbegin(), jobject.cbegin());\n CHECK(j_new == json::object());\n }\n }\n\n SECTION(\"construct from subrange\")\n {\n json const jobject = {{\"a\", \"a\"}, {\"b\", 1}, {\"c\", 17u}, {\"d\", false}, {\"e\", true}};\n json const j_new(jobject.find(\"b\"), jobject.find(\"e\"));\n CHECK(j_new == json({{\"b\", 1}, {\"c\", 17u}, {\"d\", false}}));\n }\n\n SECTION(\"incompatible iterators\")\n {\n {\n json jobject = {{\"a\", \"a\"}, {\"b\", 1}, {\"c\", 17u}, {\"d\", false}, {\"e\", true}};\n json jobject2 = {{\"a\", \"a\"}, {\"b\", 1}, {\"c\", 17u}};\n CHECK_THROWS_WITH_AS(json(jobject.begin(), jobject2.end()), \"[json.exception.invalid_iterator.201] iterators are not compatible\", json::invalid_iterator&);\n CHECK_THROWS_WITH_AS(json(jobject2.begin(), jobject.end()), \"[json.exception.invalid_iterator.201] iterators are not compatible\", json::invalid_iterator&);\n }\n {\n json const jobject = {{\"a\", \"a\"}, {\"b\", 1}, {\"c\", 17u}, {\"d\", false}, {\"e\", true}};\n json const jobject2 = {{\"a\", \"a\"}, {\"b\", 1}, {\"c\", 17u}};\n CHECK_THROWS_WITH_AS(json(jobject.cbegin(), jobject2.cend()), \"[json.exception.invalid_iterator.201] iterators are not compatible\", json::invalid_iterator&);\n CHECK_THROWS_WITH_AS(json(jobject2.cbegin(), jobject.cend()), \"[json.exception.invalid_iterator.201] iterators are not compatible\", json::invalid_iterator&);\n }\n }\n }\n\n SECTION(\"array\")\n {\n SECTION(\"json(begin(), end())\")\n {\n {\n json jarray = {1, 2, 3, 4, 5};\n json const j_new(jarray.begin(), jarray.end());\n CHECK(j_new == jarray);\n }\n {\n json const jarray = {1, 2, 3, 4, 5};\n json const j_new(jarray.cbegin(), jarray.cend());\n CHECK(j_new == jarray);\n }\n }\n\n SECTION(\"json(begin(), begin())\")\n {\n {\n json jarray = {1, 2, 3, 4, 5};\n const json j_new(jarray.begin(), jarray.begin());\n CHECK(j_new == json::array());\n }\n {\n json const jarray = {1, 2, 3, 4, 5};\n json const j_new(jarray.cbegin(), jarray.cbegin());\n CHECK(j_new == json::array());\n }\n }\n\n SECTION(\"construct from subrange\")\n {\n {\n json jarray = {1, 2, 3, 4, 5};\n json const j_new(jarray.begin() + 1, jarray.begin() + 3);\n CHECK(j_new == json({2, 3}));\n }\n {\n json const jarray = {1, 2, 3, 4, 5};\n json const j_new(jarray.cbegin() + 1, jarray.cbegin() + 3);\n CHECK(j_new == json({2, 3}));\n }\n }\n\n SECTION(\"incompatible iterators\")\n {\n {\n json jarray = {1, 2, 3, 4};\n json jarray2 = {2, 3, 4, 5};\n CHECK_THROWS_WITH_AS(json(jarray.begin(), jarray2.end()), \"[json.exception.invalid_iterator.201] iterators are not compatible\", json::invalid_iterator&);\n CHECK_THROWS_WITH_AS(json(jarray2.begin(), jarray.end()), \"[json.exception.invalid_iterator.201] iterators are not compatible\", json::invalid_iterator&);\n }\n {\n json const jarray = {1, 2, 3, 4};\n json const jarray2 = {2, 3, 4, 5};\n CHECK_THROWS_WITH_AS(json(jarray.cbegin(), jarray2.cend()), \"[json.exception.invalid_iterator.201] iterators are not compatible\", json::invalid_iterator&);\n CHECK_THROWS_WITH_AS(json(jarray2.cbegin(), jarray.cend()), \"[json.exception.invalid_iterator.201] iterators are not compatible\", json::invalid_iterator&);\n }\n }\n }\n\n SECTION(\"other values\")\n {\n SECTION(\"construct with two valid iterators\")\n {\n SECTION(\"null\")\n {\n {\n json j;\n CHECK_THROWS_WITH_AS(json(j.begin(), j.end()), \"[json.exception.invalid_iterator.206] cannot construct with iterators from null\", json::invalid_iterator&);\n }\n {\n json const j;\n CHECK_THROWS_WITH_AS(json(j.cbegin(), j.cend()), \"[json.exception.invalid_iterator.206] cannot construct with iterators from null\", json::invalid_iterator&);\n }\n }\n\n SECTION(\"string\")\n {\n {\n json j = \"foo\";\n json const j_new(j.begin(), j.end());\n CHECK(j == j_new);\n }\n {\n json const j = \"bar\";\n json const j_new(j.cbegin(), j.cend());\n CHECK(j == j_new);\n }\n }\n\n SECTION(\"number (boolean)\")\n {\n {\n json j = false;\n json const j_new(j.begin(), j.end());\n CHECK(j == j_new);\n }\n {\n json const j = true;\n json const j_new(j.cbegin(), j.cend());\n CHECK(j == j_new);\n }\n }\n\n SECTION(\"number (integer)\")\n {\n {\n json j = 17;\n json const j_new(j.begin(), j.end());\n CHECK(j == j_new);\n }\n {\n json const j = 17;\n json const j_new(j.cbegin(), j.cend());\n CHECK(j == j_new);\n }\n }\n\n SECTION(\"number (unsigned)\")\n {\n {\n json j = 17u;\n json const j_new(j.begin(), j.end());\n CHECK(j == j_new);\n }\n {\n json const j = 17u;\n json const j_new(j.cbegin(), j.cend());\n CHECK(j == j_new);\n }\n }\n\n SECTION(\"number (floating point)\")\n {\n {\n json j = 23.42;\n json const j_new(j.begin(), j.end());\n CHECK(j == j_new);\n }\n {\n json const j = 23.42;\n json const j_new(j.cbegin(), j.cend());\n CHECK(j == j_new);\n }\n }\n\n SECTION(\"binary\")\n {\n {\n json j = json::binary({1, 2, 3});\n json const j_new(j.begin(), j.end());\n CHECK((j == j_new));\n }\n {\n json const j = json::binary({1, 2, 3});\n json const j_new(j.cbegin(), j.cend());\n CHECK((j == j_new));\n }\n }\n }\n\n SECTION(\"construct with two invalid iterators\")\n {\n SECTION(\"string\")\n {\n {\n json j = \"foo\";\n CHECK_THROWS_WITH_AS(json(j.end(), j.end()), \"[json.exception.invalid_iterator.204] iterators out of range\", json::invalid_iterator&);\n CHECK_THROWS_WITH_AS(json(j.begin(), j.begin()), \"[json.exception.invalid_iterator.204] iterators out of range\", json::invalid_iterator&);\n }\n {\n json const j = \"bar\";\n CHECK_THROWS_WITH_AS(json(j.cend(), j.cend()), \"[json.exception.invalid_iterator.204] iterators out of range\", json::invalid_iterator&);\n CHECK_THROWS_WITH_AS(json(j.cbegin(), j.cbegin()), \"[json.exception.invalid_iterator.204] iterators out of range\", json::invalid_iterator&);\n }\n }\n\n SECTION(\"number (boolean)\")\n {\n {\n json j = false;\n CHECK_THROWS_WITH_AS(json(j.end(), j.end()), \"[json.exception.invalid_iterator.204] iterators out of range\", json::invalid_iterator&);\n CHECK_THROWS_WITH_AS(json(j.begin(), j.begin()), \"[json.exception.invalid_iterator.204] iterators out of range\", json::invalid_iterator&);\n }\n {\n json const j = true;\n CHECK_THROWS_WITH_AS(json(j.cend(), j.cend()), \"[json.exception.invalid_iterator.204] iterators out of range\", json::invalid_iterator&);\n CHECK_THROWS_WITH_AS(json(j.cbegin(), j.cbegin()), \"[json.exception.invalid_iterator.204] iterators out of range\", json::invalid_iterator&);\n }\n }\n\n SECTION(\"number (integer)\")\n {\n {\n json j = 17;\n CHECK_THROWS_WITH_AS(json(j.end(), j.end()), \"[json.exception.invalid_iterator.204] iterators out of range\", json::invalid_iterator&);\n CHECK_THROWS_WITH_AS(json(j.begin(), j.begin()), \"[json.exception.invalid_iterator.204] iterators out of range\", json::invalid_iterator&);\n }\n {\n json const j = 17;\n CHECK_THROWS_WITH_AS(json(j.cend(), j.cend()), \"[json.exception.invalid_iterator.204] iterators out of range\", json::invalid_iterator&);\n CHECK_THROWS_WITH_AS(json(j.cbegin(), j.cbegin()), \"[json.exception.invalid_iterator.204] iterators out of range\", json::invalid_iterator&);\n }\n }\n\n SECTION(\"number (integer)\")\n {\n {\n json j = 17u;\n CHECK_THROWS_WITH_AS(json(j.end(), j.end()), \"[json.exception.invalid_iterator.204] iterators out of range\", json::invalid_iterator&);\n CHECK_THROWS_WITH_AS(json(j.begin(), j.begin()), \"[json.exception.invalid_iterator.204] iterators out of range\", json::invalid_iterator&);\n }\n {\n json const j = 17u;\n CHECK_THROWS_WITH_AS(json(j.cend(), j.cend()), \"[json.exception.invalid_iterator.204] iterators out of range\", json::invalid_iterator&);\n CHECK_THROWS_WITH_AS(json(j.cbegin(), j.cbegin()), \"[json.exception.invalid_iterator.204] iterators out of range\", json::invalid_iterator&);\n }\n }\n\n SECTION(\"number (floating point)\")\n {\n {\n json j = 23.42;\n CHECK_THROWS_WITH_AS(json(j.end(), j.end()), \"[json.exception.invalid_iterator.204] iterators out of range\", json::invalid_iterator&);\n CHECK_THROWS_WITH_AS(json(j.begin(), j.begin()), \"[json.exception.invalid_iterator.204] iterators out of range\", json::invalid_iterator&);\n }\n {\n json const j = 23.42;\n CHECK_THROWS_WITH_AS(json(j.cend(), j.cend()), \"[json.exception.invalid_iterator.204] iterators out of range\", json::invalid_iterator&);\n CHECK_THROWS_WITH_AS(json(j.cbegin(), j.cbegin()), \"[json.exception.invalid_iterator.204] iterators out of range\", json::invalid_iterator&);\n }\n }\n }\n }\n }\n}", "messages": null, "tools": null} {"id": "9b69a43b333ffe9d", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/api/basic_json/binary.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 1901, "sha256": "2a9f1abafb2fc8c244d3c259204a2d75c70fa43c664504f0ab1cad0aca8d3a10", "text": "# nlohmann::basic_json::binary\n\n```cpp\n// (1)\nstatic basic_json binary(const typename binary_t::container_type& init);\nstatic basic_json binary(typename binary_t::container_type&& init);\n\n// (2)\nstatic basic_json binary(const typename binary_t::container_type& init,\n std::uint8_t subtype);\nstatic basic_json binary(typename binary_t::container_type&& init,\n std::uint8_t subtype);\n```\n\n1. Creates a JSON binary array value from a given binary container.\n2. Creates a JSON binary array value from a given binary container with subtype.\n \nBinary values are part of various binary formats, such as CBOR, MessagePack, and BSON. This constructor is used to\ncreate a value for serialization to those formats.\n\n## Parameters\n\n`init` (in)\n: container containing bytes to use as a binary type\n\n`subtype` (in)\n: subtype to use in CBOR, MessagePack, and BSON\n\n## Return value\n\nJSON binary array value\n\n## Exception safety\n\nStrong guarantee: if an exception is thrown, there are no changes in the JSON value.\n\n## Complexity\n\nLinear in the size of `init`; constant for `typename binary_t::container_type&& init` versions.\n\n## Notes\n\nNote, this function exists because of the difficulty in correctly specifying the correct template overload in the\nstandard value ctor, as both JSON arrays and JSON binary arrays are backed with some form of a `std::vector`. Because\nJSON binary arrays are a non-standard extension, it was decided that it would be best to prevent automatic\ninitialization of a binary array type, for backwards compatibility and so it does not happen on accident.\n\n## Examples\n\n??? example\n\n The following code shows how to create a binary value.\n \n ```cpp\n --8<-- \"examples/binary.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/binary.output\"\n ```\n\n## Version history\n\n- Added in version 3.8.0.", "messages": null, "tools": null} {"id": "9b74a2a104a6ab52", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/diagnostic_positions.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 2291, "sha256": "519454297151c06634d4bf1fa776cc484268f4af8ba0e6ef3781f5c7d63a7335", "text": "#include \n\n#define JSON_DIAGNOSTIC_POSITIONS 1\n#include \n\nusing json = nlohmann::json;\n\nint main()\n{\n std::string json_string = R\"(\n {\n \"address\": {\n \"street\": \"Fake Street\",\n \"housenumber\": 1\n }\n }\n )\";\n json j = json::parse(json_string);\n\n std::cout << \"Root diagnostic positions: \\n\";\n std::cout << \"\\tstart_pos: \" << j.start_pos() << '\\n';\n std::cout << \"\\tend_pos:\" << j.end_pos() << \"\\n\";\n std::cout << \"Original string: \\n\";\n std::cout << \"{\\n \\\"address\\\": {\\n \\\"street\\\": \\\"Fake Street\\\",\\n \\\"housenumber\\\": 1\\n }\\n }\" << \"\\n\";\n std::cout << \"Parsed string: \\n\";\n std::cout << json_string.substr(j.start_pos(), j.end_pos() - j.start_pos()) << \"\\n\\n\";\n\n std::cout << \"address diagnostic positions: \\n\";\n std::cout << \"\\tstart_pos:\" << j[\"address\"].start_pos() << '\\n';\n std::cout << \"\\tend_pos:\" << j[\"address\"].end_pos() << \"\\n\\n\";\n std::cout << \"Original string: \\n\";\n std::cout << \"{ \\\"street\\\": \\\"Fake Street\\\",\\n \\\"housenumber\\\": 1\\n }\" << \"\\n\";\n std::cout << \"Parsed string: \\n\";\n std::cout << json_string.substr(j[\"address\"].start_pos(), j[\"address\"].end_pos() - j[\"address\"].start_pos()) << \"\\n\\n\";\n\n std::cout << \"street diagnostic positions: \\n\";\n std::cout << \"\\tstart_pos:\" << j[\"address\"][\"street\"].start_pos() << '\\n';\n std::cout << \"\\tend_pos:\" << j[\"address\"][\"street\"].end_pos() << \"\\n\\n\";\n std::cout << \"Original string: \\n\";\n std::cout << \"\\\"Fake Street\\\"\" << \"\\n\";\n std::cout << \"Parsed string: \\n\";\n std::cout << json_string.substr(j[\"address\"][\"street\"].start_pos(), j[\"address\"][\"street\"].end_pos() - j[\"address\"][\"street\"].start_pos()) << \"\\n\\n\";\n\n std::cout << \"housenumber diagnostic positions: \\n\";\n std::cout << \"\\tstart_pos:\" << j[\"address\"][\"housenumber\"].start_pos() << '\\n';\n std::cout << \"\\tend_pos:\" << j[\"address\"][\"housenumber\"].end_pos() << \"\\n\\n\";\n std::cout << \"Original string: \\n\";\n std::cout << \"1\" << \"\\n\";\n std::cout << \"Parsed string: \\n\";\n std::cout << json_string.substr(j[\"address\"][\"housenumber\"].start_pos(), j[\"address\"][\"housenumber\"].end_pos() - j[\"address\"][\"housenumber\"].start_pos()) << \"\\n\\n\";\n}", "messages": null, "tools": null} {"id": "9bb5143ca71892ef", "category": "code", "domain": "code", "source": "ripgrep", "license": "MIT OR Unlicense", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/feature.rs", "lang": "rust", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/BurntSushi/ripgrep", "commit": "3fce3b5bb0236da2df6d99672afb8a719642eca7", "collector": "tools/harvest.py"}, "chars": 38453, "sha256": "def8a1c460f48c9a8dc43f792caf3c46daf382353483ed422c003a15dc45bdb6", "text": "use crate::hay::{SHERLOCK, SHERLOCK_CRLF};\nuse crate::util::{Dir, TestCommand, sort_lines};\n\n// See: https://github.com/BurntSushi/ripgrep/issues/1\nrgtest!(f1_sjis, |dir: Dir, mut cmd: TestCommand| {\n dir.create_bytes(\n \"foo\",\n b\"\\x84Y\\x84u\\x84\\x82\\x84|\\x84\\x80\\x84{ \\x84V\\x84\\x80\\x84|\\x84}\\x84\\x83\"\n );\n cmd.arg(\"-Esjis\").arg(\"Шерлок Холмс\");\n eqnice!(\"foo:Шерлок Холмс\\n\", cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/1\nrgtest!(f1_utf16_auto, |dir: Dir, mut cmd: TestCommand| {\n dir.create_bytes(\n \"foo\",\n b\"\\xff\\xfe(\\x045\\x04@\\x04;\\x04>\\x04:\\x04 \\x00%\\x04>\\x04;\\x04<\\x04A\\x04\"\n );\n cmd.arg(\"Шерлок Холмс\");\n eqnice!(\"foo:Шерлок Холмс\\n\", cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/1\nrgtest!(f1_utf16_explicit, |dir: Dir, mut cmd: TestCommand| {\n dir.create_bytes(\n \"foo\",\n b\"\\xff\\xfe(\\x045\\x04@\\x04;\\x04>\\x04:\\x04 \\x00%\\x04>\\x04;\\x04<\\x04A\\x04\"\n );\n cmd.arg(\"-Eutf-16le\").arg(\"Шерлок Холмс\");\n eqnice!(\"foo:Шерлок Холмс\\n\", cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/1\nrgtest!(f1_eucjp, |dir: Dir, mut cmd: TestCommand| {\n dir.create_bytes(\n \"foo\",\n b\"\\xa7\\xba\\xa7\\xd6\\xa7\\xe2\\xa7\\xdd\\xa7\\xe0\\xa7\\xdc \\xa7\\xb7\\xa7\\xe0\\xa7\\xdd\\xa7\\xde\\xa7\\xe3\"\n );\n cmd.arg(\"-Eeuc-jp\").arg(\"Шерлок Холмс\");\n eqnice!(\"foo:Шерлок Холмс\\n\", cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/1\nrgtest!(f1_unknown_encoding, |_: Dir, mut cmd: TestCommand| {\n cmd.arg(\"-Efoobar\").assert_non_empty_stderr();\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/1\nrgtest!(f1_replacement_encoding, |_: Dir, mut cmd: TestCommand| {\n cmd.arg(\"-Ecsiso2022kr\").assert_non_empty_stderr();\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/7\nrgtest!(f7, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n dir.create(\"pat\", \"Sherlock\\nHolmes\");\n\n let expected = \"\\\nFor the Doctor Watsons of this world, as opposed to the Sherlock\nHolmeses, success in the province of detective work must always\nbe, to a very large extent, the result of luck. Sherlock Holmes\n\";\n eqnice!(expected, cmd.arg(\"-fpat\").arg(\"sherlock\").stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/7\nrgtest!(f7_stdin, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n\n let expected = \"\\\nsherlock:For the Doctor Watsons of this world, as opposed to the Sherlock\nsherlock:be, to a very large extent, the result of luck. Sherlock Holmes\n\";\n eqnice!(expected, cmd.arg(\"-f-\").pipe(b\"Sherlock\"));\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/20\nrgtest!(f20_no_filename, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n cmd.arg(\"--no-filename\");\n\n let expected = \"\\\nFor the Doctor Watsons of this world, as opposed to the Sherlock\nbe, to a very large extent, the result of luck. Sherlock Holmes\n\";\n eqnice!(expected, cmd.arg(\"--no-filename\").arg(\"Sherlock\").stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/34\nrgtest!(f34_only_matching, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n\n let expected = \"\\\nsherlock:Sherlock\nsherlock:Sherlock\n\";\n eqnice!(expected, cmd.arg(\"-o\").arg(\"Sherlock\").stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/34\nrgtest!(f34_only_matching_line_column, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n\n let expected = \"\\\nsherlock:1:57:Sherlock\nsherlock:3:49:Sherlock\n\";\n cmd.arg(\"-o\").arg(\"--column\").arg(\"-n\").arg(\"Sherlock\");\n eqnice!(expected, cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/45\nrgtest!(f45_relative_cwd, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\".not-an-ignore\", \"foo\\n/bar\");\n dir.create_dir(\"bar\");\n dir.create_dir(\"baz/bar\");\n dir.create_dir(\"baz/baz/bar\");\n dir.create(\"bar/test\", \"test\");\n dir.create(\"baz/bar/test\", \"test\");\n dir.create(\"baz/baz/bar/test\", \"test\");\n dir.create(\"baz/foo\", \"test\");\n dir.create(\"baz/test\", \"test\");\n dir.create(\"foo\", \"test\");\n dir.create(\"test\", \"test\");\n\n cmd.arg(\"-l\").arg(\"test\");\n\n // First, get a baseline without applying ignore rules.\n let expected = \"\nbar/test\nbaz/bar/test\nbaz/baz/bar/test\nbaz/foo\nbaz/test\nfoo\ntest\n\";\n eqnice!(sort_lines(expected), sort_lines(&cmd.stdout()));\n\n // Now try again with the ignore file activated.\n cmd.arg(\"--ignore-file\").arg(\".not-an-ignore\");\n let expected = \"\nbaz/bar/test\nbaz/baz/bar/test\nbaz/test\ntest\n\";\n eqnice!(sort_lines(expected), sort_lines(&cmd.stdout()));\n\n // Now do it again, but inside the baz directory. Since the ignore file\n // is interpreted relative to the CWD, this will cause the /bar anchored\n // pattern to filter out baz/bar, which is a subtle difference between true\n // parent ignore files and manually specified ignore files.\n let mut cmd = dir.command();\n cmd.args(&[\"--ignore-file\", \"../.not-an-ignore\", \"-l\", \"test\"]);\n cmd.current_dir(\"baz\");\n let expected = \"\nbaz/bar/test\ntest\n\";\n eqnice!(sort_lines(expected), sort_lines(&cmd.stdout()));\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/45\nrgtest!(f45_precedence_with_others, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\".not-an-ignore\", \"*.log\");\n dir.create(\".ignore\", \"!imp.log\");\n dir.create(\"imp.log\", \"test\");\n dir.create(\"wat.log\", \"test\");\n\n cmd.arg(\"--ignore-file\").arg(\".not-an-ignore\").arg(\"test\");\n eqnice!(\"imp.log:test\\n\", cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/45\nrgtest!(f45_precedence_internal, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\".not-an-ignore1\", \"*.log\");\n dir.create(\".not-an-ignore2\", \"!imp.log\");\n dir.create(\"imp.log\", \"test\");\n dir.create(\"wat.log\", \"test\");\n\n cmd.args(&[\n \"--ignore-file\",\n \".not-an-ignore1\",\n \"--ignore-file\",\n \".not-an-ignore2\",\n \"test\",\n ]);\n eqnice!(\"imp.log:test\\n\", cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/68\nrgtest!(f68_no_ignore_vcs, |dir: Dir, mut cmd: TestCommand| {\n dir.create_dir(\".git\");\n dir.create(\".gitignore\", \"foo\");\n dir.create(\".ignore\", \"bar\");\n dir.create(\"foo\", \"test\");\n dir.create(\"bar\", \"test\");\n\n eqnice!(\"foo:test\\n\", cmd.arg(\"--no-ignore-vcs\").arg(\"test\").stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/70\nrgtest!(f70_smart_case, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n\n let expected = \"\\\nsherlock:For the Doctor Watsons of this world, as opposed to the Sherlock\nsherlock:be, to a very large extent, the result of luck. Sherlock Holmes\n\";\n eqnice!(expected, cmd.arg(\"-S\").arg(\"sherlock\").stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/89\nrgtest!(f89_files_with_matches, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n\n cmd.arg(\"--null\").arg(\"--files-with-matches\").arg(\"Sherlock\");\n eqnice!(\"sherlock\\x00\", cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/89\nrgtest!(f89_files_without_match, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n dir.create(\"file.py\", \"foo\");\n\n cmd.arg(\"--null\").arg(\"--files-without-match\").arg(\"Sherlock\");\n eqnice!(\"file.py\\x00\", cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/89\nrgtest!(f89_count, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n\n cmd.arg(\"--null\").arg(\"--count\").arg(\"Sherlock\");\n eqnice!(\"sherlock\\x002\\n\", cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/89\nrgtest!(f89_files, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n\n eqnice!(\"sherlock\\x00\", cmd.arg(\"--null\").arg(\"--files\").stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/89\nrgtest!(f89_match, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n\n let expected = \"\\\nsherlock\\x00For the Doctor Watsons of this world, as opposed to the Sherlock\nsherlock\\x00Holmeses, success in the province of detective work must always\nsherlock\\x00be, to a very large extent, the result of luck. Sherlock Holmes\nsherlock\\x00can extract a clew from a wisp of straw or a flake of cigar ash;\n\";\n eqnice!(expected, cmd.arg(\"--null\").arg(\"-C1\").arg(\"Sherlock\").stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/109\nrgtest!(f109_max_depth, |dir: Dir, mut cmd: TestCommand| {\n dir.create_dir(\"one\");\n dir.create(\"one/pass\", \"far\");\n dir.create_dir(\"one/too\");\n dir.create(\"one/too/many\", \"far\");\n\n cmd.arg(\"--maxdepth\").arg(\"2\").arg(\"far\");\n eqnice!(\"one/pass:far\\n\", cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/124\nrgtest!(f109_case_sensitive_part1, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"foo\", \"tEsT\");\n\n cmd.arg(\"--smart-case\").arg(\"--case-sensitive\").arg(\"test\").assert_err();\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/124\nrgtest!(f109_case_sensitive_part2, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"foo\", \"tEsT\");\n cmd.arg(\"--ignore-case\").arg(\"--case-sensitive\").arg(\"test\").assert_err();\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/129\nrgtest!(f129_matches, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"foo\", \"test\\ntest abcdefghijklmnopqrstuvwxyz test\");\n\n let expected = \"foo:test\\nfoo:[Omitted long matching line]\\n\";\n eqnice!(expected, cmd.arg(\"-M26\").arg(\"test\").stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/129\nrgtest!(f129_context, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"foo\", \"test\\nabcdefghijklmnopqrstuvwxyz\");\n\n let expected = \"foo:test\\nfoo-[Omitted long context line]\\n\";\n eqnice!(expected, cmd.arg(\"-M20\").arg(\"-C1\").arg(\"test\").stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/129\nrgtest!(f129_replace, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"foo\", \"test\\ntest abcdefghijklmnopqrstuvwxyz test\");\n\n let expected = \"foo:foo\\nfoo:[Omitted long line with 2 matches]\\n\";\n eqnice!(expected, cmd.arg(\"-M26\").arg(\"-rfoo\").arg(\"test\").stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/159\nrgtest!(f159_max_count, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"foo\", \"test\\ntest\");\n\n eqnice!(\"foo:test\\n\", cmd.arg(\"-m1\").arg(\"test\").stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/159\nrgtest!(f159_max_count_zero, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"foo\", \"test\\ntest\");\n\n cmd.arg(\"-m0\").arg(\"test\").assert_err();\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/196\nrgtest!(f196_persistent_config, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n cmd.arg(\"sherlock\").arg(\"sherlock\");\n\n // Make sure we get no matches by default.\n cmd.assert_err();\n\n // Now add our config file, and make sure it impacts ripgrep.\n dir.create(\".ripgreprc\", \"--ignore-case\");\n cmd.cmd().env(\"RIPGREP_CONFIG_PATH\", \".ripgreprc\");\n\n let expected = \"\\\nFor the Doctor Watsons of this world, as opposed to the Sherlock\nbe, to a very large extent, the result of luck. Sherlock Holmes\n\";\n eqnice!(expected, cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/243\nrgtest!(f243_column_line, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"foo\", \"test\");\n\n eqnice!(\"foo:1:1:test\\n\", cmd.arg(\"--column\").arg(\"test\").stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/263\nrgtest!(f263_sort_files, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"foo\", \"test\");\n dir.create(\"abc\", \"test\");\n dir.create(\"zoo\", \"test\");\n dir.create(\"bar\", \"test\");\n\n let expected = \"abc:test\\nbar:test\\nfoo:test\\nzoo:test\\n\";\n eqnice!(expected, cmd.arg(\"--sort-files\").arg(\"test\").stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/263\nrgtest!(f263_sort_files_reverse, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"foo\", \"test\");\n dir.create(\"abc\", \"test\");\n dir.create(\"zoo\", \"test\");\n dir.create(\"bar\", \"test\");\n\n let expected = \"zoo:test\\nfoo:test\\nbar:test\\nabc:test\\n\";\n eqnice!(expected, cmd.arg(\"--sortr=path\").arg(\"test\").stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/275\nrgtest!(f275_pathsep, |dir: Dir, mut cmd: TestCommand| {\n dir.create_dir(\"foo\");\n dir.create(\"foo/bar\", \"test\");\n\n cmd.arg(\"test\").arg(\"--path-separator\").arg(\"Z\");\n eqnice!(\"fooZbar:test\\n\", cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/362\nrgtest!(f362_dfa_size_limit, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n\n // This should fall back to the nfa engine but should still produce the\n // expected result.\n cmd.arg(\"--dfa-size-limit\").arg(\"10\").arg(r\"For\\s\").arg(\"sherlock\");\n\n let expected = \"\\\nFor the Doctor Watsons of this world, as opposed to the Sherlock\n\";\n eqnice!(expected, cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/362\nrgtest!(f362_exceeds_regex_size_limit, |dir: Dir, mut cmd: TestCommand| {\n // --regex-size-limit doesn't apply to PCRE2.\n if dir.is_pcre2() {\n return;\n }\n cmd.arg(\"--regex-size-limit\").arg(\"10K\").arg(r\"[0-9]\\w+\").assert_err();\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/362\n#[cfg(target_pointer_width = \"32\")]\nrgtest!(\n f362_u64_to_narrow_usize_overflow,\n |dir: Dir, mut cmd: TestCommand| {\n // --dfa-size-limit doesn't apply to PCRE2.\n if dir.is_pcre2() {\n return;\n }\n dir.create_size(\"foo\", 1000000);\n\n // 2^35 * 2^20 is ok for u64, but not for usize\n cmd.arg(\"--dfa-size-limit\").arg(\"34359738368M\").arg(\"--files\");\n cmd.assert_err();\n }\n);\n\n// See: https://github.com/BurntSushi/ripgrep/issues/411\nrgtest!(\n f411_single_threaded_search_stats,\n |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n\n let lines = cmd.arg(\"-j1\").arg(\"--stats\").arg(\"Sherlock\").stdout();\n assert!(lines.contains(\"Sherlock\"));\n assert!(lines.contains(\"2 matched lines\"));\n assert!(lines.contains(\"1 files contained matches\"));\n assert!(lines.contains(\"1 files searched\"));\n assert!(lines.contains(\"seconds\"));\n }\n);\n\nrgtest!(f411_parallel_search_stats, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock_1\", SHERLOCK);\n dir.create(\"sherlock_2\", SHERLOCK);\n\n let lines = cmd.arg(\"-j2\").arg(\"--stats\").arg(\"Sherlock\").stdout();\n assert!(lines.contains(\"4 matched lines\"));\n assert!(lines.contains(\"2 files contained matches\"));\n assert!(lines.contains(\"2 files searched\"));\n assert!(lines.contains(\"seconds\"));\n});\n\nrgtest!(\n f411_single_threaded_quiet_search_stats,\n |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n\n let lines = cmd\n .arg(\"--quiet\")\n .arg(\"-j1\")\n .arg(\"--stats\")\n .arg(\"Sherlock\")\n .stdout();\n assert!(!lines.contains(\"Sherlock\"));\n assert!(lines.contains(\"2 matched lines\"));\n assert!(lines.contains(\"1 files contained matches\"));\n assert!(lines.contains(\"1 files searched\"));\n assert!(lines.contains(\"seconds\"));\n }\n);\n\nrgtest!(f411_parallel_quiet_search_stats, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock_1\", SHERLOCK);\n dir.create(\"sherlock_2\", SHERLOCK);\n\n let lines =\n cmd.arg(\"-j2\").arg(\"--quiet\").arg(\"--stats\").arg(\"Sherlock\").stdout();\n assert!(!lines.contains(\"Sherlock\"));\n assert!(lines.contains(\"4 matched lines\"));\n assert!(lines.contains(\"2 files contained matches\"));\n assert!(lines.contains(\"2 files searched\"));\n assert!(lines.contains(\"seconds\"));\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/416\nrgtest!(f416_crlf, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK_CRLF);\n cmd.arg(\"--crlf\").arg(r\"Sherlock$\").arg(\"sherlock\");\n\n let expected = \"\\\nFor the Doctor Watsons of this world, as opposed to the Sherlock\\r\n\";\n eqnice!(expected, cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/416\nrgtest!(f416_crlf_multiline, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK_CRLF);\n cmd.arg(\"--crlf\").arg(\"-U\").arg(r\"Sherlock$\").arg(\"sherlock\");\n\n let expected = \"\\\nFor the Doctor Watsons of this world, as opposed to the Sherlock\\r\n\";\n eqnice!(expected, cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/416\nrgtest!(f416_crlf_only_matching, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK_CRLF);\n cmd.arg(\"--crlf\").arg(\"-o\").arg(r\"Sherlock$\").arg(\"sherlock\");\n\n let expected = \"\\\nSherlock\\r\n\";\n eqnice!(expected, cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/419\nrgtest!(f419_zero_as_shortcut_for_null, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n\n cmd.arg(\"-0\").arg(\"--count\").arg(\"Sherlock\");\n eqnice!(\"sherlock\\x002\\n\", cmd.stdout());\n});\n\nrgtest!(f740_passthru, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"file\", \"\\nfoo\\nbar\\nfoobar\\n\\nbaz\\n\");\n dir.create(\"patterns\", \"foo\\nbar\\n\");\n\n // We can't assume that the way colour specs are translated to ANSI\n // sequences will remain stable, and --replace doesn't currently work with\n // pass-through, so for now we don't actually test the match sub-strings\n let common_args = &[\"-n\", \"--passthru\"];\n let foo_expected = \"\\\n1-\n2:foo\n3-bar\n4:foobar\n5-\n6-baz\n\";\n\n // With single pattern\n cmd.args(common_args).arg(\"foo\").arg(\"file\");\n eqnice!(foo_expected, cmd.stdout());\n\n let foo_bar_expected = \"\\\n1-\n2:foo\n3:bar\n4:foobar\n5-\n6-baz\n\";\n\n // With multiple -e patterns\n let mut cmd = dir.command();\n cmd.args(common_args);\n cmd.args(&[\"-e\", \"foo\", \"-e\", \"bar\", \"file\"]);\n eqnice!(foo_bar_expected, cmd.stdout());\n\n // With multiple -f patterns\n let mut cmd = dir.command();\n cmd.args(common_args);\n cmd.args(&[\"-f\", \"patterns\", \"file\"]);\n eqnice!(foo_bar_expected, cmd.stdout());\n\n // -c should override\n let mut cmd = dir.command();\n cmd.args(common_args);\n cmd.args(&[\"-c\", \"foo\", \"file\"]);\n eqnice!(\"2\\n\", cmd.stdout());\n\n let only_foo_expected = \"\\\n1-\n2:foo\n3-bar\n4:foo\n5-\n6-baz\n\";\n\n // -o should work\n let mut cmd = dir.command();\n cmd.args(common_args);\n cmd.args(&[\"-o\", \"foo\", \"file\"]);\n eqnice!(only_foo_expected, cmd.stdout());\n\n let replace_foo_expected = \"\\\n1-\n2:wat\n3-bar\n4:watbar\n5-\n6-baz\n\";\n\n // -r should work\n let mut cmd = dir.command();\n cmd.args(common_args);\n cmd.args(&[\"-r\", \"wat\", \"foo\", \"file\"]);\n eqnice!(replace_foo_expected, cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/948\nrgtest!(f948_exit_code_match, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n cmd.arg(\".\");\n\n cmd.assert_exit_code(0);\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/948\nrgtest!(f948_exit_code_no_match, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n cmd.arg(\"NADA\");\n\n cmd.assert_exit_code(1);\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/948\nrgtest!(f948_exit_code_error, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n cmd.arg(\"*\");\n\n cmd.assert_exit_code(2);\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/917\nrgtest!(f917_trim, |dir: Dir, mut cmd: TestCommand| {\n const SHERLOCK: &'static str = \"\\\nzzz\n For the Doctor Watsons of this world, as opposed to the Sherlock\n Holmeses, success in the province of detective work must always\n\\tbe, to a very large extent, the result of luck. Sherlock Holmes\n can extract a clew from a wisp of straw or a flake of cigar ash;\nbut Doctor Watson has to have it taken out for him and dusted,\n and exhibited clearly, with a label attached.\n\";\n dir.create(\"sherlock\", SHERLOCK);\n cmd.args(&[\"-n\", \"-B1\", \"-A2\", \"--trim\", \"Holmeses\", \"sherlock\"]);\n\n let expected = \"\\\n2-For the Doctor Watsons of this world, as opposed to the Sherlock\n3:Holmeses, success in the province of detective work must always\n4-be, to a very large extent, the result of luck. Sherlock Holmes\n5-can extract a clew from a wisp of straw or a flake of cigar ash;\n\";\n eqnice!(expected, cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/917\n//\n// This is like f917_trim, except this tests that trimming occurs even when the\n// whitespace is part of a match.\nrgtest!(f917_trim_match, |dir: Dir, mut cmd: TestCommand| {\n const SHERLOCK: &'static str = \"\\\nzzz\n For the Doctor Watsons of this world, as opposed to the Sherlock\n Holmeses, success in the province of detective work must always\n\\tbe, to a very large extent, the result of luck. Sherlock Holmes\n can extract a clew from a wisp of straw or a flake of cigar ash;\nbut Doctor Watson has to have it taken out for him and dusted,\n and exhibited clearly, with a label attached.\n\";\n dir.create(\"sherlock\", SHERLOCK);\n cmd.args(&[\"-n\", \"-B1\", \"-A2\", \"--trim\", r\"\\s+Holmeses\", \"sherlock\"]);\n\n let expected = \"\\\n2-For the Doctor Watsons of this world, as opposed to the Sherlock\n3:Holmeses, success in the province of detective work must always\n4-be, to a very large extent, the result of luck. Sherlock Holmes\n5-can extract a clew from a wisp of straw or a flake of cigar ash;\n\";\n eqnice!(expected, cmd.stdout());\n});\n\nrgtest!(f917_trim_multi_standard, |dir: Dir, mut cmd: TestCommand| {\n const HAYSTACK: &str = \" 0123456789abcdefghijklmnopqrstuvwxyz\";\n dir.create(\"haystack\", HAYSTACK);\n cmd.args(&[\"--multiline\", \"--trim\", \"-r$0\", \"--no-filename\", r\"a\\n?bc\"]);\n\n let expected = \"0123456789abcdefghijklmnopqrstuvwxyz\\n\";\n eqnice!(expected, cmd.stdout());\n});\n\nrgtest!(f917_trim_max_columns_normal, |dir: Dir, mut cmd: TestCommand| {\n const HAYSTACK: &str = \" 0123456789abcdefghijklmnopqrstuvwxyz\";\n dir.create(\"haystack\", HAYSTACK);\n cmd.args(&[\n \"--trim\",\n \"--max-columns-preview\",\n \"-M8\",\n \"--no-filename\",\n \"abc\",\n ]);\n\n let expected = \"01234567 [... omitted end of long line]\\n\";\n eqnice!(expected, cmd.stdout());\n});\n\nrgtest!(f917_trim_max_columns_matches, |dir: Dir, mut cmd: TestCommand| {\n const HAYSTACK: &str = \" 0123456789abcdefghijklmnopqrstuvwxyz\";\n dir.create(\"haystack\", HAYSTACK);\n cmd.args(&[\n \"--trim\",\n \"--max-columns-preview\",\n \"-M8\",\n \"--color=always\",\n \"--colors=path:none\",\n \"--no-filename\",\n \"abc\",\n ]);\n\n let expected = \"01234567 [... 1 more match]\\n\";\n eqnice!(expected, cmd.stdout());\n});\n\nrgtest!(\n f917_trim_max_columns_multi_standard,\n |dir: Dir, mut cmd: TestCommand| {\n const HAYSTACK: &str = \" 0123456789abcdefghijklmnopqrstuvwxyz\";\n dir.create(\"haystack\", HAYSTACK);\n cmd.args(&[\n \"--multiline\",\n \"--trim\",\n \"--max-columns-preview\",\n \"-M8\",\n // Force the \"slow\" printing path without actually\n // putting colors in the output.\n \"--color=always\",\n \"--colors=path:none\",\n \"--no-filename\",\n r\"a\\n?bc\",\n ]);\n\n let expected = \"01234567 [... 1 more match]\\n\";\n eqnice!(expected, cmd.stdout());\n }\n);\n\nrgtest!(\n f917_trim_max_columns_multi_only_matching,\n |dir: Dir, mut cmd: TestCommand| {\n const HAYSTACK: &str = \" 0123456789abcdefghijklmnopqrstuvwxyz\";\n dir.create(\"haystack\", HAYSTACK);\n cmd.args(&[\n \"--multiline\",\n \"--trim\",\n \"--max-columns-preview\",\n \"-M8\",\n \"--only-matching\",\n \"--no-filename\",\n r\".*a\\n?bc.*\",\n ]);\n\n let expected = \"01234567 [... 0 more matches]\\n\";\n eqnice!(expected, cmd.stdout());\n }\n);\n\nrgtest!(\n f917_trim_max_columns_multi_per_match,\n |dir: Dir, mut cmd: TestCommand| {\n const HAYSTACK: &str = \" 0123456789abcdefghijklmnopqrstuvwxyz\";\n dir.create(\"haystack\", HAYSTACK);\n cmd.args(&[\n \"--multiline\",\n \"--trim\",\n \"--max-columns-preview\",\n \"-M8\",\n \"--vimgrep\",\n \"--no-filename\",\n r\".*a\\n?bc.*\",\n ]);\n\n let expected = \"1:1:01234567 [... 0 more matches]\\n\";\n eqnice!(expected, cmd.stdout());\n }\n);\n\n// See: https://github.com/BurntSushi/ripgrep/issues/993\nrgtest!(f993_null_data, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"test\", \"foo\\x00bar\\x00\\x00\\x00baz\\x00\");\n cmd.arg(\"--null-data\").arg(r\".+\").arg(\"test\");\n\n // If we just used -a instead of --null-data, then the result would include\n // all NUL bytes.\n let expected = \"foo\\x00bar\\x00baz\\x00\";\n eqnice!(expected, cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/1078\n//\n// N.B. There are many more tests in the grep-printer crate.\nrgtest!(f1078_max_columns_preview1, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n cmd.args(&[\n \"-M46\",\n \"--max-columns-preview\",\n \"exhibited|dusted|has to have it\",\n ]);\n\n let expected = \"\\\nsherlock:but Doctor Watson has to have it taken out for [... omitted end of long line]\nsherlock:and exhibited clearly, with a label attached.\n\";\n eqnice!(expected, cmd.stdout());\n});\n\nrgtest!(f1078_max_columns_preview2, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n cmd.args(&[\n \"-M43\",\n \"--max-columns-preview\",\n // Doing a replacement forces ripgrep to show the number of remaining\n // matches. Normally, this happens by default when printing a tty with\n // colors.\n \"-rxxx\",\n \"exhibited|dusted|has to have it\",\n ]);\n\n let expected = \"\\\nsherlock:but Doctor Watson xxx taken out for him and [... 1 more match]\nsherlock:and xxx clearly, with a label attached.\n\";\n eqnice!(expected, cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/1138\nrgtest!(f1138_no_ignore_dot, |dir: Dir, mut cmd: TestCommand| {\n dir.create_dir(\".git\");\n dir.create(\".gitignore\", \"foo\");\n dir.create(\".ignore\", \"bar\");\n dir.create(\".fzf-ignore\", \"quux\");\n dir.create(\"foo\", \"\");\n dir.create(\"bar\", \"\");\n dir.create(\"quux\", \"\");\n\n cmd.arg(\"--sort\").arg(\"path\").arg(\"--files\");\n eqnice!(\"quux\\n\", cmd.stdout());\n eqnice!(\"bar\\nquux\\n\", cmd.arg(\"--no-ignore-dot\").stdout());\n eqnice!(\"bar\\n\", cmd.arg(\"--ignore-file\").arg(\".fzf-ignore\").stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/1155\nrgtest!(f1155_auto_hybrid_regex, |dir: Dir, mut cmd: TestCommand| {\n // No sense in testing a hybrid regex engine with only one engine!\n if !dir.is_pcre2() {\n return;\n }\n\n dir.create(\"sherlock\", SHERLOCK);\n cmd.arg(\"--no-pcre2\").arg(\"--auto-hybrid-regex\").arg(r\"(?<=the )Sherlock\");\n\n let expected = \"\\\nsherlock:For the Doctor Watsons of this world, as opposed to the Sherlock\n\";\n eqnice!(expected, cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/1207\n//\n// Tests if without encoding 'none' flag null bytes are consumed by automatic\n// encoding detection.\nrgtest!(f1207_auto_encoding, |dir: Dir, mut cmd: TestCommand| {\n dir.create_bytes(\"foo\", b\"\\xFF\\xFE\\x00\\x62\");\n cmd.arg(\"-a\").arg(\"\\\\x00\").arg(\"foo\");\n cmd.assert_exit_code(1);\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/1207\n//\n// Tests if encoding 'none' flag does treat file as raw bytes\nrgtest!(f1207_ignore_encoding, |dir: Dir, mut cmd: TestCommand| {\n // PCRE2 chokes on this test because it can't search invalid non-UTF-8\n // and the point of this test is to search raw UTF-16.\n if dir.is_pcre2() {\n return;\n }\n\n dir.create_bytes(\"foo\", b\"\\xFF\\xFE\\x00\\x62\");\n cmd.arg(\"--encoding\").arg(\"none\").arg(\"-a\").arg(\"\\\\x00\").arg(\"foo\");\n eqnice!(\"\\u{FFFD}\\u{FFFD}\\x00b\\n\", cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/1414\nrgtest!(f1414_no_require_git, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\".gitignore\", \"foo\");\n dir.create(\"foo\", \"\");\n dir.create(\"bar\", \"\");\n\n let stdout = cmd.args(&[\"--sort\", \"path\", \"--files\"]).stdout();\n eqnice!(\"bar\\nfoo\\n\", stdout);\n\n let stdout =\n cmd.args(&[\"--sort\", \"path\", \"--files\", \"--no-require-git\"]).stdout();\n eqnice!(\"bar\\n\", stdout);\n\n let stdout = cmd\n .args(&[\n \"--sort\",\n \"path\",\n \"--files\",\n \"--no-require-git\",\n \"--require-git\",\n ])\n .stdout();\n eqnice!(\"bar\\nfoo\\n\", stdout);\n});\n\n// See: https://github.com/BurntSushi/ripgrep/pull/1420\nrgtest!(f1420_no_ignore_exclude, |dir: Dir, mut cmd: TestCommand| {\n dir.create_dir(\".git/info\");\n dir.create(\".git/info/exclude\", \"foo\");\n dir.create(\"bar\", \"\");\n dir.create(\"foo\", \"\");\n\n cmd.arg(\"--sort\").arg(\"path\").arg(\"--files\");\n eqnice!(\"bar\\n\", cmd.stdout());\n eqnice!(\"bar\\nfoo\\n\", cmd.arg(\"--no-ignore-exclude\").stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/pull/1466\nrgtest!(f1466_no_ignore_files, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\".myignore\", \"bar\");\n dir.create(\"bar\", \"\");\n dir.create(\"foo\", \"\");\n\n // Test that --no-ignore-files disables --ignore-file.\n // And that --ignore-files overrides --no-ignore-files.\n cmd.arg(\"--sort\").arg(\"path\").arg(\"--files\");\n eqnice!(\"bar\\nfoo\\n\", cmd.stdout());\n eqnice!(\"foo\\n\", cmd.arg(\"--ignore-file\").arg(\".myignore\").stdout());\n eqnice!(\"bar\\nfoo\\n\", cmd.arg(\"--no-ignore-files\").stdout());\n eqnice!(\"foo\\n\", cmd.arg(\"--ignore-files\").stdout());\n\n // Test that the -u flag does not disable --ignore-file.\n let mut cmd = dir.command();\n cmd.arg(\"--sort\").arg(\"path\").arg(\"--files\");\n cmd.arg(\"--ignore-file\").arg(\".myignore\");\n eqnice!(\"foo\\n\", cmd.stdout());\n eqnice!(\"foo\\n\", cmd.arg(\"-u\").stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/pull/2361\nrgtest!(f2361_sort_nested_files, |dir: Dir, mut cmd: TestCommand| {\n use std::{thread::sleep, time::Duration};\n\n if crate::util::is_cross() {\n return;\n }\n dir.create(\"foo\", \"1\");\n sleep(Duration::from_millis(200));\n dir.create_dir(\"dir\");\n sleep(Duration::from_millis(200));\n dir.create(dir.path().join(\"dir\").join(\"bar\"), \"1\");\n\n cmd.arg(\"--sort\").arg(\"accessed\").arg(\"--files\");\n eqnice!(\"foo\\ndir/bar\\n\", cmd.stdout());\n\n dir.create(\"foo\", \"2\");\n sleep(Duration::from_millis(200));\n dir.create(dir.path().join(\"dir\").join(\"bar\"), \"2\");\n sleep(Duration::from_millis(200));\n\n cmd.arg(\"--sort\").arg(\"accessed\").arg(\"--files\");\n eqnice!(\"foo\\ndir/bar\\n\", cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/1404\nrgtest!(f1404_nothing_searched_warning, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\".ignore\", \"ignored-dir/**\");\n dir.create_dir(\"ignored-dir\");\n dir.create(\"ignored-dir/foo\", \"needle\");\n\n // Test that, if ripgrep searches only ignored folders/files, then there\n // is a non-zero exit code.\n cmd.arg(\"needle\");\n cmd.assert_err();\n\n // Test that we actually get an error message that we expect.\n let output = cmd.raw_output();\n let stderr = String::from_utf8_lossy(&output.stderr);\n let expected = \"\\\n rg: No files were searched, which means ripgrep probably applied \\\n a filter you didn't expect.\\n\\\n Running with --debug will show why files are being skipped.\\n\\\n \";\n eqnice!(expected, stderr);\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/1404\nrgtest!(f1404_nothing_searched_ignored, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\".ignore\", \"ignored-dir/**\");\n dir.create_dir(\"ignored-dir\");\n dir.create(\"ignored-dir/foo\", \"needle\");\n\n // Test that, if ripgrep searches only ignored folders/files, then there\n // is a non-zero exit code.\n cmd.arg(\"--no-messages\").arg(\"needle\");\n cmd.assert_err();\n\n // But since --no-messages is given, there should not be any error message\n // printed.\n let output = cmd.raw_output();\n let stderr = String::from_utf8_lossy(&output.stderr);\n let expected = \"\";\n eqnice!(expected, stderr);\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/1842\nrgtest!(f1842_field_context_separator, |dir: Dir, _: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n\n // Test the default.\n let base = &[\"-n\", \"-A1\", \"Doctor Watsons\", \"sherlock\"];\n let expected = \"\\\n1:For the Doctor Watsons of this world, as opposed to the Sherlock\n2-Holmeses, success in the province of detective work must always\n\";\n eqnice!(expected, dir.command().args(base).stdout());\n\n // Test that it can be overridden.\n let mut args = vec![\"--field-context-separator\", \"!\"];\n args.extend(base);\n let expected = \"\\\n1:For the Doctor Watsons of this world, as opposed to the Sherlock\n2!Holmeses, success in the province of detective work must always\n\";\n eqnice!(expected, dir.command().args(&args).stdout());\n\n // Test that it can use multiple bytes.\n let mut args = vec![\"--field-context-separator\", \"!!\"];\n args.extend(base);\n let expected = \"\\\n1:For the Doctor Watsons of this world, as opposed to the Sherlock\n2!!Holmeses, success in the province of detective work must always\n\";\n eqnice!(expected, dir.command().args(&args).stdout());\n\n // Test that unescaping works.\n let mut args = vec![\"--field-context-separator\", r\"\\x7F\"];\n args.extend(base);\n let expected = \"\\\n1:For the Doctor Watsons of this world, as opposed to the Sherlock\n2\\x7FHolmeses, success in the province of detective work must always\n\";\n eqnice!(expected, dir.command().args(&args).stdout());\n\n // Test that an empty separator is OK.\n let mut args = vec![\"--field-context-separator\", r\"\"];\n args.extend(base);\n let expected = \"\\\n1:For the Doctor Watsons of this world, as opposed to the Sherlock\n2Holmeses, success in the province of detective work must always\n\";\n eqnice!(expected, dir.command().args(&args).stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/1842\nrgtest!(f1842_field_match_separator, |dir: Dir, _: TestCommand| {\n dir.create(\"sherlock\", SHERLOCK);\n\n // Test the default.\n let base = &[\"-n\", \"Doctor Watsons\", \"sherlock\"];\n let expected = \"\\\n1:For the Doctor Watsons of this world, as opposed to the Sherlock\n\";\n eqnice!(expected, dir.command().args(base).stdout());\n\n // Test that it can be overridden.\n let mut args = vec![\"--field-match-separator\", \"!\"];\n args.extend(base);\n let expected = \"\\\n1!For the Doctor Watsons of this world, as opposed to the Sherlock\n\";\n eqnice!(expected, dir.command().args(&args).stdout());\n\n // Test that it can use multiple bytes.\n let mut args = vec![\"--field-match-separator\", \"!!\"];\n args.extend(base);\n let expected = \"\\\n1!!For the Doctor Watsons of this world, as opposed to the Sherlock\n\";\n eqnice!(expected, dir.command().args(&args).stdout());\n\n // Test that unescaping works.\n let mut args = vec![\"--field-match-separator\", r\"\\x7F\"];\n args.extend(base);\n let expected = \"\\\n1\\x7FFor the Doctor Watsons of this world, as opposed to the Sherlock\n\";\n eqnice!(expected, dir.command().args(&args).stdout());\n\n // Test that an empty separator is OK.\n let mut args = vec![\"--field-match-separator\", r\"\"];\n args.extend(base);\n let expected = \"\\\n1For the Doctor Watsons of this world, as opposed to the Sherlock\n\";\n eqnice!(expected, dir.command().args(&args).stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/2288\nrgtest!(f2288_context_partial_override, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"test\", \"1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n\");\n cmd.args(&[\"-C1\", \"-A2\", \"5\", \"test\"]);\n eqnice!(\"4\\n5\\n6\\n7\\n\", cmd.stdout());\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/2288\nrgtest!(\n f2288_context_partial_override_rev,\n |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"test\", \"1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n9\\n\");\n cmd.args(&[\"-A2\", \"-C1\", \"5\", \"test\"]);\n eqnice!(\"4\\n5\\n6\\n7\\n\", cmd.stdout());\n }\n);\n\nrgtest!(no_context_sep, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"test\", \"foo\\nctx\\nbar\\nctx\\nfoo\\nctx\");\n cmd.args(&[\"-A1\", \"--no-context-separator\", \"foo\", \"test\"]);\n eqnice!(\"foo\\nctx\\nfoo\\nctx\\n\", cmd.stdout());\n});\n\nrgtest!(no_context_sep_overrides, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"test\", \"foo\\nctx\\nbar\\nctx\\nfoo\\nctx\");\n cmd.args(&[\n \"-A1\",\n \"--context-separator\",\n \"AAA\",\n \"--no-context-separator\",\n \"foo\",\n \"test\",\n ]);\n eqnice!(\"foo\\nctx\\nfoo\\nctx\\n\", cmd.stdout());\n});\n\nrgtest!(no_context_sep_overridden, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"test\", \"foo\\nctx\\nbar\\nctx\\nfoo\\nctx\");\n cmd.args(&[\n \"-A1\",\n \"--no-context-separator\",\n \"--context-separator\",\n \"AAA\",\n \"foo\",\n \"test\",\n ]);\n eqnice!(\"foo\\nctx\\nAAA\\nfoo\\nctx\\n\", cmd.stdout());\n});\n\nrgtest!(context_sep, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"test\", \"foo\\nctx\\nbar\\nctx\\nfoo\\nctx\");\n cmd.args(&[\"-A1\", \"--context-separator\", \"AAA\", \"foo\", \"test\"]);\n eqnice!(\"foo\\nctx\\nAAA\\nfoo\\nctx\\n\", cmd.stdout());\n});\n\nrgtest!(context_sep_default, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"test\", \"foo\\nctx\\nbar\\nctx\\nfoo\\nctx\");\n cmd.args(&[\"-A1\", \"foo\", \"test\"]);\n eqnice!(\"foo\\nctx\\n--\\nfoo\\nctx\\n\", cmd.stdout());\n});\n\nrgtest!(context_sep_empty, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"test\", \"foo\\nctx\\nbar\\nctx\\nfoo\\nctx\");\n cmd.args(&[\"-A1\", \"--context-separator\", \"\", \"foo\", \"test\"]);\n eqnice!(\"foo\\nctx\\n\\nfoo\\nctx\\n\", cmd.stdout());\n});\n\nrgtest!(no_unicode, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"test\", \"δ\");\n cmd.arg(\"-i\").arg(\"--no-unicode\").arg(\"Δ\").assert_err();\n});\n\n// See: https://github.com/BurntSushi/ripgrep/issues/1790\nrgtest!(stop_on_nonmatch, |dir: Dir, mut cmd: TestCommand| {\n dir.create(\"test\", \"line1\\nline2\\nline3\\nline4\\nline5\");\n cmd.args(&[\"--stop-on-nonmatch\", \"[235]\"]);\n eqnice!(\"test:line2\\ntest:line3\\n\", cmd.stdout());\n});", "messages": null, "tools": null} {"id": "9c208eea64937112", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/src/unit-byte_container_with_subtype.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 2699, "sha256": "e4a6aacffe49b0a37c0c44d52c71452440df423519bb35e2a5daf816f326c5f3", "text": "// __ _____ _____ _____\n// __| | __| | | | JSON for Modern C++ (supporting code)\n// | | |__ | | | | | | version 3.12.0\n// |_____|_____|_____|_|___| https://github.com/nlohmann/json\n//\n// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann \n// SPDX-License-Identifier: MIT\n\n#include \"doctest_compatibility.h\"\n\n#include \nusing nlohmann::json;\n\nTEST_CASE(\"byte_container_with_subtype\")\n{\n using subtype_type = nlohmann::byte_container_with_subtype>::subtype_type;\n\n SECTION(\"empty container\")\n {\n nlohmann::byte_container_with_subtype> container;\n\n CHECK(!container.has_subtype());\n CHECK(container.subtype() == static_cast(-1));\n\n container.clear_subtype();\n CHECK(!container.has_subtype());\n CHECK(container.subtype() == static_cast(-1));\n\n container.set_subtype(42);\n CHECK(container.has_subtype());\n CHECK(container.subtype() == 42);\n }\n\n SECTION(\"subtyped container\")\n {\n nlohmann::byte_container_with_subtype> container({}, 42);\n CHECK(container.has_subtype());\n CHECK(container.subtype() == 42);\n\n container.clear_subtype();\n CHECK(!container.has_subtype());\n CHECK(container.subtype() == static_cast(-1));\n }\n\n SECTION(\"comparisons\")\n {\n std::vector const bytes = {{0xCA, 0xFE, 0xBA, 0xBE}};\n nlohmann::byte_container_with_subtype> container1;\n nlohmann::byte_container_with_subtype> container2({}, 42);\n nlohmann::byte_container_with_subtype> container3(bytes);\n nlohmann::byte_container_with_subtype> container4(bytes, 42);\n\n CHECK(container1 == container1);\n CHECK(container1 != container2);\n CHECK(container1 != container3);\n CHECK(container1 != container4);\n CHECK(container2 != container1);\n CHECK(container2 == container2);\n CHECK(container2 != container3);\n CHECK(container2 != container4);\n CHECK(container3 != container1);\n CHECK(container3 != container2);\n CHECK(container3 == container3);\n CHECK(container3 != container4);\n CHECK(container4 != container1);\n CHECK(container4 != container2);\n CHECK(container4 != container3);\n CHECK(container4 == container4);\n\n container3.clear();\n container4.clear();\n\n CHECK(container1 == container3);\n CHECK(container2 == container4);\n }\n}", "messages": null, "tools": null} {"id": "9c99b82a5a889bba", "category": "code", "domain": "code", "source": "requests", "license": "Apache-2.0", "license_url": "https://spdx.org/licenses/Apache-2.0.html", "path": "src/requests/compat.py", "lang": "python", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/psf/requests", "commit": "1f6589ec3a1ee910f9a65cc3ceac60b26677bc0e", "collector": "tools/harvest.py"}, "chars": 2493, "sha256": "bb916eed3bca663af8667746782390007c061ac1d5f32925b075fb1e31a2838e", "text": "\"\"\"\nrequests.compat\n~~~~~~~~~~~~~~~\n\nThis module previously handled import compatibility issues\nbetween Python 2 and Python 3. It remains for backwards\ncompatibility until the next major version.\n\"\"\"\n\n# pyright: reportUnusedImport=false\n\nfrom __future__ import annotations\n\nimport importlib\nimport sys\nfrom types import ModuleType\nfrom typing import TYPE_CHECKING\n\n# -------\n# urllib3\n# -------\nfrom urllib3 import __version__ as urllib3_version\n\n# Detect which major version of urllib3 is being used.\ntry:\n is_urllib3_1 = int(urllib3_version.split(\".\")[0]) == 1\nexcept (TypeError, AttributeError):\n # If we can't discern a version, prefer old functionality.\n is_urllib3_1 = True\n\n# -------------------\n# Character Detection\n# -------------------\n\n\ndef _resolve_char_detection() -> ModuleType | None:\n \"\"\"Find supported character detection libraries.\"\"\"\n chardet = None\n for lib in (\"chardet\", \"charset_normalizer\"):\n if chardet is None:\n try:\n chardet = importlib.import_module(lib)\n except ImportError:\n pass\n return chardet\n\n\nif TYPE_CHECKING:\n import chardet\nelse:\n chardet = _resolve_char_detection()\n\n# -------\n# Pythons\n# -------\n\n# Syntax sugar.\n_ver = sys.version_info\n\n#: Python 2.x?\nis_py2 = _ver[0] == 2\n\n#: Python 3.x?\nis_py3 = _ver[0] == 3\n\n# json/simplejson module import resolution\nhas_simplejson = False\ntry:\n import simplejson as json # type: ignore[import-not-found]\n\n has_simplejson = True\nexcept ImportError:\n import json\n\nif has_simplejson:\n from simplejson import JSONDecodeError # type: ignore[import-not-found]\nelse:\n from json import JSONDecodeError\n\n# Keep OrderedDict for backwards compatibility.\nfrom collections import OrderedDict\nfrom collections.abc import Callable, Mapping, MutableMapping\nfrom http import cookiejar as cookielib\nfrom http.cookies import Morsel\nfrom io import StringIO\n\n# --------------\n# Legacy Imports\n# --------------\nfrom urllib.parse import (\n quote,\n quote_plus,\n unquote,\n unquote_plus,\n urldefrag,\n urlencode,\n urljoin,\n urlparse,\n urlsplit,\n urlunparse,\n)\nfrom urllib.request import (\n getproxies,\n getproxies_environment,\n parse_http_list,\n proxy_bypass,\n proxy_bypass_environment, # type: ignore[attr-defined] # https://github.com/python/cpython/issues/145331\n)\n\nbuiltin_str = str\nstr = str\nbytes = bytes\nbasestring = (str, bytes)\nnumeric_types = (int, float)\ninteger_types = (int,)", "messages": null, "tools": null} {"id": "9cfd72b5a40d2683", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/assets/vite.config-encoded-base.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 772, "sha256": "2bbc50142b3b02385a36d6e3f2d4ce9f817d8baa7777291a28eef0e602ff46d5", "text": "import { defineConfig } from 'vite'\nimport baseConfig from './vite.config.js'\n\n/** see `ports` variable in test-utils.ts */\nconst port = 9524\n\nexport default defineConfig({\n ...baseConfig,\n // Vite should auto-encode this as `/foo%20bar/` internally\n base: '/foo bar/',\n server: {\n port,\n strictPort: true,\n },\n build: {\n ...baseConfig.build,\n outDir: 'dist/encoded-base',\n watch: null,\n minify: false,\n assetsInlineLimit: 0,\n rolldownOptions: {\n output: {\n entryFileNames: 'entries/[name].js',\n chunkFileNames: 'chunks/[name]-[hash].js',\n assetFileNames: 'other-assets/[name]-[hash][extname]',\n },\n },\n },\n preview: {\n port,\n strictPort: true,\n },\n cacheDir: 'node_modules/.vite-encoded-base',\n})", "messages": null, "tools": null} {"id": "9d22de29f8fa86a1", "category": "code", "domain": "code", "source": "fmt", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "test/util.h", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/fmtlib/fmt", "commit": "4f645a8d5d7aa6f8c5ba57e9af0396e4761d3f81", "collector": "tools/harvest.py"}, "chars": 1819, "sha256": "1e4360fbf156029dffd605b889175cefba6e8ff205065582bd58ffa48c109684", "text": "// Formatting library for C++ - test utilities\n//\n// Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors\n// All rights reserved.\n//\n// For the license information refer to format.h.\n\n#include \n#include \n#include \n#include \n\n#include \"fmt/os.h\"\n\n#ifdef _MSC_VER\n# define FMT_VSNPRINTF vsprintf_s\n#else\n# define FMT_VSNPRINTF vsnprintf\n#endif\n\ntemplate \nvoid safe_sprintf(char (&buffer)[SIZE], const char* format, ...) {\n std::va_list args;\n va_start(args, format);\n FMT_VSNPRINTF(buffer, SIZE, format, args);\n va_end(args);\n}\n\nextern const char* const file_content;\n\n// Opens a buffered file for reading.\nauto open_buffered_file(FILE** fp = nullptr) -> fmt::buffered_file;\n\ntemplate class basic_test_string {\n private:\n std::basic_string value_;\n\n static const Char empty[];\n\n public:\n explicit basic_test_string(const Char* value = empty) : value_(value) {}\n\n auto value() const -> const std::basic_string& { return value_; }\n};\n\ntemplate const Char basic_test_string::empty[] = {0};\n\nusing test_string = basic_test_string;\nusing test_wstring = basic_test_string;\n\ntemplate \nauto operator<<(std::basic_ostream& os, const basic_test_string& s)\n -> std::basic_ostream& {\n os << s.value();\n return os;\n}\n\nclass date {\n int year_, month_, day_;\n\n public:\n date(int year, int month, int day) : year_(year), month_(month), day_(day) {}\n\n auto year() const -> int { return year_; }\n auto month() const -> int { return month_; }\n auto day() const -> int { return day_; }\n};\n\n// Returns a locale with the given name if available or classic locale\n// otherwise.\nauto get_locale(const char* name, const char* alt_name = nullptr)\n -> std::locale;", "messages": null, "tools": null} {"id": "9d2cbcc3fe76cc6f", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/css-no-codesplit/vite.config.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 272, "sha256": "a9eda792defcdac6c93d5f0ba37ebbdf7831716a5476ae81327ca1b05c9f685b", "text": "import { resolve } from 'node:path'\nimport { defineConfig } from 'vite'\n\nexport default defineConfig({\n input: {\n index: resolve(import.meta.dirname, './index.html'),\n sub: resolve(import.meta.dirname, './sub.html'),\n },\n build: {\n cssCodeSplit: false,\n },\n})", "messages": null, "tools": null} {"id": "9dd4eb59ca02a0e1", "category": "code", "domain": "code", "source": "fmt", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "include/fmt/chrono.h", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/fmtlib/fmt", "commit": "4f645a8d5d7aa6f8c5ba57e9af0396e4761d3f81", "collector": "tools/harvest.py"}, "chars": 77366, "sha256": "2a02df3b42d68685a077f2fba22cdeafcf5f3d5ee61fd1d50ce51dc7fdf5f853", "text": "// Formatting library for C++ - chrono support\n//\n// Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors\n// All rights reserved.\n//\n// For the license information refer to format.h.\n\n#ifndef FMT_CHRONO_H_\n#define FMT_CHRONO_H_\n\n#ifndef FMT_MODULE\n# include \n# include \n# include // std::isfinite\n# include // std::memcpy\n# include \n# include \n# include \n# include \n# include \n#endif\n\n#include \"format.h\"\n\nFMT_BEGIN_NAMESPACE\n\n// Enable safe chrono durations, unless explicitly disabled.\n#ifndef FMT_SAFE_DURATION_CAST\n# define FMT_SAFE_DURATION_CAST 1\n#endif\n#if FMT_SAFE_DURATION_CAST\n\n// For conversion between std::chrono::durations without undefined\n// behaviour or erroneous results.\n// This is a stripped down version of duration_cast, for inclusion in fmt.\n// See https://github.com/pauldreik/safe_duration_cast\n//\n// Copyright Paul Dreik 2019\nnamespace safe_duration_cast {\n\n// DEPRECATED!\ntemplate ::value &&\n std::numeric_limits::is_signed ==\n std::numeric_limits::is_signed)>\nFMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec)\n -> To {\n ec = 0;\n using F = std::numeric_limits;\n using T = std::numeric_limits;\n static_assert(F::is_integer, \"From must be integral\");\n static_assert(T::is_integer, \"To must be integral\");\n\n // A and B are both signed, or both unsigned.\n if FMT_CONSTEXPR20 (F::digits <= T::digits) {\n // From fits in To without any problem.\n } else {\n // From does not always fit in To, resort to a dynamic check.\n if (from < (T::min)() || from > (T::max)()) {\n // outside range.\n ec = 1;\n return {};\n }\n }\n return static_cast(from);\n}\n\n/// Converts From to To, without loss. If the dynamic value of from\n/// can't be converted to To without loss, ec is set.\ntemplate ::value &&\n std::numeric_limits::is_signed !=\n std::numeric_limits::is_signed)>\nFMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec)\n -> To {\n ec = 0;\n using F = std::numeric_limits;\n using T = std::numeric_limits;\n static_assert(F::is_integer, \"From must be integral\");\n static_assert(T::is_integer, \"To must be integral\");\n\n if FMT_CONSTEXPR20 (F::is_signed && !T::is_signed) {\n // From may be negative, not allowed!\n if (fmt::detail::is_negative(from)) {\n ec = 1;\n return {};\n }\n // From is positive. Can it always fit in To?\n if (F::digits > T::digits &&\n from > static_cast(detail::max_value())) {\n ec = 1;\n return {};\n }\n }\n\n if (!F::is_signed && T::is_signed && F::digits >= T::digits &&\n from > static_cast(detail::max_value())) {\n ec = 1;\n return {};\n }\n return static_cast(from); // Lossless conversion.\n}\n\ntemplate ::value)>\nFMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec)\n -> To {\n ec = 0;\n return from;\n} // function\n\n// clang-format off\n/**\n * converts From to To if possible, otherwise ec is set.\n *\n * input | output\n * ---------------------------------|---------------\n * NaN | NaN\n * Inf | Inf\n * normal, fits in output | converted (possibly lossy)\n * normal, does not fit in output | ec is set\n * subnormal | best effort\n * -Inf | -Inf\n */\n// clang-format on\ntemplate ::value)>\nFMT_CONSTEXPR auto safe_float_conversion(const From from, int& ec) -> To {\n ec = 0;\n using T = std::numeric_limits;\n static_assert(std::is_floating_point::value, \"From must be floating\");\n static_assert(std::is_floating_point::value, \"To must be floating\");\n\n // catch the only happy case\n if (std::isfinite(from)) {\n if (from >= T::lowest() && from <= (T::max)()) {\n return static_cast(from);\n }\n // not within range.\n ec = 1;\n return {};\n }\n\n // nan and inf will be preserved\n return static_cast(from);\n} // function\n\ntemplate ::value)>\nFMT_CONSTEXPR auto safe_float_conversion(const From from, int& ec) -> To {\n ec = 0;\n static_assert(std::is_floating_point::value, \"From must be floating\");\n return from;\n}\n\n/// Safe duration_cast between floating point durations\ntemplate ::value),\n FMT_ENABLE_IF(std::is_floating_point::value)>\nauto safe_duration_cast(std::chrono::duration from,\n int& ec) -> To {\n using From = std::chrono::duration;\n ec = 0;\n\n // the basic idea is that we need to convert from count() in the from type\n // to count() in the To type, by multiplying it with this:\n struct Factor\n : std::ratio_divide {};\n\n static_assert(Factor::num > 0, \"num must be positive\");\n static_assert(Factor::den > 0, \"den must be positive\");\n\n // the conversion is like this: multiply from.count() with Factor::num\n // /Factor::den and convert it to To::rep, all this without\n // overflow/underflow. let's start by finding a suitable type that can hold\n // both To, From and Factor::num\n using IntermediateRep =\n typename std::common_type::type;\n\n // force conversion of From::rep -> IntermediateRep to be safe,\n // even if it will never happen be narrowing in this context.\n IntermediateRep count =\n safe_float_conversion(from.count(), ec);\n if (ec) {\n return {};\n }\n\n // multiply with Factor::num without overflow or underflow\n if FMT_CONSTEXPR20 (Factor::num != 1) {\n constexpr auto max1 = detail::max_value() /\n static_cast(Factor::num);\n if (count > max1) {\n ec = 1;\n return {};\n }\n constexpr auto min1 = std::numeric_limits::lowest() /\n static_cast(Factor::num);\n if (count < min1) {\n ec = 1;\n return {};\n }\n count *= static_cast(Factor::num);\n }\n\n // this can't go wrong, right? den>0 is checked earlier.\n if FMT_CONSTEXPR20 (Factor::den != 1) {\n using common_t = typename std::common_type::type;\n count /= static_cast(Factor::den);\n }\n\n // convert to the to type, safely\n using ToRep = typename To::rep;\n\n const ToRep tocount = safe_float_conversion(count, ec);\n if (ec) {\n return {};\n }\n return To{tocount};\n}\n} // namespace safe_duration_cast\n#endif\n\nnamespace detail {\n\n// Check if std::chrono::utc_time is available.\n#ifdef FMT_USE_UTC_TIME\n// Use the provided definition.\n#elif defined(__cpp_lib_chrono)\n# define FMT_USE_UTC_TIME (__cpp_lib_chrono >= 201907L)\n#else\n# define FMT_USE_UTC_TIME 0\n#endif\n#if FMT_USE_UTC_TIME\nusing utc_clock = std::chrono::utc_clock;\n#else\nstruct utc_clock {\n template void to_sys(T);\n};\n#endif\n\n// Check if std::chrono::local_time is available.\n#ifdef FMT_USE_LOCAL_TIME\n// Use the provided definition.\n#elif defined(__cpp_lib_chrono)\n# define FMT_USE_LOCAL_TIME (__cpp_lib_chrono >= 201907L)\n#else\n# define FMT_USE_LOCAL_TIME 0\n#endif\n#if FMT_USE_LOCAL_TIME\nusing local_t = std::chrono::local_t;\n#else\nstruct local_t {};\n#endif\n\n} // namespace detail\n\ntemplate \nusing sys_time = std::chrono::time_point;\n\ntemplate \nusing utc_time = std::chrono::time_point;\n\ntemplate \nusing local_time = std::chrono::time_point;\n\nnamespace detail {\n\n// Prevents expansion of a preceding token as a function-style macro.\n// Usage: f FMT_NOMACRO()\n#define FMT_NOMACRO\n\ntemplate struct null {};\ninline auto gmtime_r(...) -> null<> { return null<>(); }\ninline auto gmtime_s(...) -> null<> { return null<>(); }\n\n// It is defined here and not in ostream.h because the latter has expensive\n// includes.\ntemplate class formatbuf : public StreamBuf {\n private:\n using char_type = typename StreamBuf::char_type;\n using streamsize = decltype(std::declval().sputn(nullptr, 0));\n using int_type = typename StreamBuf::int_type;\n using traits_type = typename StreamBuf::traits_type;\n\n buffer& buffer_;\n\n public:\n explicit formatbuf(buffer& buf) : buffer_(buf) {}\n\n protected:\n // The put area is always empty. This makes the implementation simpler and has\n // the advantage that the streambuf and the buffer are always in sync and\n // sputc never writes into uninitialized memory. A disadvantage is that each\n // call to sputc always results in a (virtual) call to overflow. There is no\n // disadvantage here for sputn since this always results in a call to xsputn.\n\n auto overflow(int_type ch) -> int_type override {\n if (!traits_type::eq_int_type(ch, traits_type::eof()))\n buffer_.push_back(static_cast(ch));\n return ch;\n }\n\n auto xsputn(const char_type* s, streamsize count) -> streamsize override {\n buffer_.append(s, s + count);\n return count;\n }\n};\n\ninline auto get_classic_locale() -> const std::locale& {\n static const auto& locale = std::locale::classic();\n return locale;\n}\n\ntemplate struct codecvt_result {\n static constexpr size_t max_size = 32;\n CodeUnit buf[max_size];\n CodeUnit* end;\n};\n\ntemplate \nvoid write_codecvt(codecvt_result& out, string_view in,\n const std::locale& loc) {\n FMT_PRAGMA_CLANG(diagnostic push)\n FMT_PRAGMA_CLANG(diagnostic ignored \"-Wdeprecated\")\n auto& f = std::use_facet>(loc);\n FMT_PRAGMA_CLANG(diagnostic pop)\n auto mb = std::mbstate_t();\n const char* from_next = nullptr;\n auto result = f.in(mb, in.begin(), in.end(), from_next, std::begin(out.buf),\n std::end(out.buf), out.end);\n if (result != std::codecvt_base::ok)\n FMT_THROW(format_error(\"failed to format time\"));\n}\n\ntemplate \nauto write_encoded_tm_str(OutputIt out, string_view in, const std::locale& loc)\n -> OutputIt {\n if (detail::use_utf8 && loc != get_classic_locale()) {\n // char16_t and char32_t codecvts are broken in MSVC (linkage errors) and\n // gcc-4.\n#if FMT_MSC_VERSION != 0 || \\\n (defined(__GLIBCXX__) && \\\n (!defined(_GLIBCXX_USE_DUAL_ABI) || _GLIBCXX_USE_DUAL_ABI == 0))\n // The _GLIBCXX_USE_DUAL_ABI macro is always defined in libstdc++ from gcc-5\n // and newer.\n using code_unit = wchar_t;\n#else\n using code_unit = char32_t;\n#endif\n\n using unit_t = codecvt_result;\n unit_t unit;\n write_codecvt(unit, in, loc);\n // In UTF-8 is used one to four one-byte code units.\n auto u =\n to_utf8>();\n if (!u.convert({unit.buf, to_unsigned(unit.end - unit.buf)}))\n FMT_THROW(format_error(\"failed to format time\"));\n return copy(u.c_str(), u.c_str() + u.size(), out);\n }\n return copy(in.data(), in.data() + in.size(), out);\n}\n\ntemplate ::value)>\nauto write_tm_str(OutputIt out, string_view sv, const std::locale& loc)\n -> OutputIt {\n codecvt_result unit;\n write_codecvt(unit, sv, loc);\n return copy(unit.buf, unit.end, out);\n}\n\ntemplate ::value)>\nauto write_tm_str(OutputIt out, string_view sv, const std::locale& loc)\n -> OutputIt {\n return write_encoded_tm_str(out, sv, loc);\n}\n\ntemplate \ninline void do_write(buffer& buf, const std::tm& time,\n const std::locale& loc, char format, char modifier) {\n auto&& format_buf = formatbuf>(buf);\n auto&& os = std::basic_ostream(&format_buf);\n os.imbue(loc);\n const auto& facet = std::use_facet>(loc);\n auto end = facet.put(os, os, Char(' '), &time, format, modifier);\n if (end.failed()) FMT_THROW(format_error(\"failed to format time\"));\n}\n\ntemplate ::value)>\nauto write(OutputIt out, const std::tm& time, const std::locale& loc,\n char format, char modifier = 0) -> OutputIt {\n auto&& buf = get_buffer(out);\n do_write(buf, time, loc, format, modifier);\n return get_iterator(buf, out);\n}\n\ntemplate ::value)>\nauto write(OutputIt out, const std::tm& time, const std::locale& loc,\n char format, char modifier = 0) -> OutputIt {\n auto&& buf = basic_memory_buffer();\n do_write(buf, time, loc, format, modifier);\n return write_encoded_tm_str(out, string_view(buf.data(), buf.size()), loc);\n}\n\ntemplate \nusing is_similar_arithmetic_type =\n bool_constant<(std::is_integral::value && std::is_integral::value) ||\n (std::is_floating_point::value &&\n std::is_floating_point::value)>;\n\nFMT_NORETURN inline void throw_duration_error() {\n FMT_THROW(format_error(\"cannot format duration\"));\n}\n\n// Cast one integral duration to another with an overflow check.\ntemplate ::value&&\n std::is_integral::value)>\nauto duration_cast(std::chrono::duration from) -> To {\n#if !FMT_SAFE_DURATION_CAST\n return std::chrono::duration_cast(from);\n#else\n // The conversion factor: to.count() == factor * from.count().\n using factor = std::ratio_divide;\n\n using common_rep = typename std::common_type::type;\n common_rep count = from.count(); // This conversion is lossless.\n\n // Multiply from.count() by factor and check for overflow.\n if FMT_CONSTEXPR20 (factor::num != 1) {\n if (count > max_value() / factor::num) throw_duration_error();\n const auto min = (std::numeric_limits::min)() / factor::num;\n if (!std::is_unsigned::value && count < min)\n throw_duration_error();\n count *= factor::num;\n }\n if FMT_CONSTEXPR20 (factor::den != 1) count /= factor::den;\n int ec = 0;\n auto to =\n To(safe_duration_cast::lossless_integral_conversion(\n count, ec));\n if (ec) throw_duration_error();\n return to;\n#endif\n}\n\ntemplate ::value&&\n std::is_floating_point::value)>\nauto duration_cast(std::chrono::duration from) -> To {\n#if FMT_SAFE_DURATION_CAST\n // Preserve infinity and NaN.\n if (!isfinite(from.count())) return static_cast(from.count());\n // Throwing version of safe_duration_cast is only available for\n // integer to integer or float to float casts.\n int ec;\n To to = safe_duration_cast::safe_duration_cast(from, ec);\n if (ec) throw_duration_error();\n return to;\n#else\n // Standard duration cast, may overflow.\n return std::chrono::duration_cast(from);\n#endif\n}\n\ntemplate ::value)>\nauto duration_cast(std::chrono::duration from) -> To {\n // Mixed integer <-> float cast is not supported by safe duration_cast.\n return std::chrono::duration_cast(from);\n}\n\ntemplate \nauto to_time_t(sys_time time_point) -> std::time_t {\n // Cannot use std::chrono::system_clock::to_time_t since this would first\n // require a cast to std::chrono::system_clock::time_point, which could\n // overflow.\n return detail::duration_cast>(\n time_point.time_since_epoch())\n .count();\n}\n\n} // namespace detail\n\nFMT_BEGIN_EXPORT\n\n/**\n * Converts given time since epoch as `std::time_t` value into calendar time,\n * expressed in Coordinated Universal Time (UTC). Unlike `std::gmtime`, this\n * function is thread-safe on most platforms.\n */\ninline auto gmtime(std::time_t time) -> std::tm {\n struct dispatcher {\n std::time_t time_;\n std::tm tm_;\n\n inline dispatcher(std::time_t t) : time_(t) {}\n\n inline auto run() -> bool {\n using namespace fmt::detail;\n return handle(gmtime_r(&time_, &tm_));\n }\n\n inline auto handle(std::tm* tm) -> bool { return tm != nullptr; }\n\n inline auto handle(detail::null<>) -> bool {\n using namespace fmt::detail;\n return fallback(gmtime_s(&tm_, &time_));\n }\n\n inline auto fallback(int res) -> bool { return res == 0; }\n\n#if !FMT_MSC_VERSION\n inline auto fallback(detail::null<>) -> bool {\n std::tm* tm = std::gmtime(&time_);\n if (tm) tm_ = *tm;\n return tm != nullptr;\n }\n#endif\n };\n auto gt = dispatcher(time);\n // Too big time values may be unsupported.\n if (!gt.run()) FMT_THROW(format_error(\"time_t value out of range\"));\n return gt.tm_;\n}\n\ntemplate \ninline auto gmtime(sys_time time_point) -> std::tm {\n return gmtime(detail::to_time_t(time_point));\n}\n\nnamespace detail {\n\n// Writes two-digit numbers a, b and c separated by sep to buf.\n// The method by Pavel Novikov based on\n// https://johnnylee-sde.github.io/Fast-unsigned-integer-to-time-string/.\ninline void write_digit2_separated(char* buf, unsigned a, unsigned b,\n unsigned c, char sep) {\n ullong digits = a | (b << 24) | (static_cast(c) << 48);\n // Convert each value to BCD.\n // We have x = a * 10 + b and we want to convert it to BCD y = a * 16 + b.\n // The difference is\n // y - x = a * 6\n // a can be found from x:\n // a = floor(x / 10)\n // then\n // y = x + a * 6 = x + floor(x / 10) * 6\n // floor(x / 10) is (x * 205) >> 11 (needs 16 bits).\n digits += (((digits * 205) >> 11) & 0x000f00000f00000f) * 6;\n // Put low nibbles to high bytes and high nibbles to low bytes.\n digits = ((digits & 0x00f00000f00000f0) >> 4) |\n ((digits & 0x000f00000f00000f) << 8);\n auto usep = static_cast(sep);\n // Add ASCII '0' to each digit byte and insert separators.\n digits |= 0x3030003030003030 | (usep << 16) | (usep << 40);\n\n constexpr size_t len = 8;\n if (is_big_endian()) {\n char tmp[len];\n std::memcpy(tmp, &digits, len);\n std::reverse_copy(tmp, tmp + len, buf);\n } else {\n std::memcpy(buf, &digits, len);\n }\n}\n\ntemplate \nFMT_CONSTEXPR inline auto get_units() -> const char* {\n if (std::is_same::value) return \"as\";\n if (std::is_same::value) return \"fs\";\n if (std::is_same::value) return \"ps\";\n if (std::is_same::value) return \"ns\";\n if (std::is_same::value)\n return detail::use_utf8 ? \"µs\" : \"us\";\n if (std::is_same::value) return \"ms\";\n if (std::is_same::value) return \"cs\";\n if (std::is_same::value) return \"ds\";\n if (std::is_same>::value) return \"s\";\n if (std::is_same::value) return \"das\";\n if (std::is_same::value) return \"hs\";\n if (std::is_same::value) return \"ks\";\n if (std::is_same::value) return \"Ms\";\n if (std::is_same::value) return \"Gs\";\n if (std::is_same::value) return \"Ts\";\n if (std::is_same::value) return \"Ps\";\n if (std::is_same::value) return \"Es\";\n if (std::is_same>::value) return \"min\";\n if (std::is_same>::value) return \"h\";\n if (std::is_same>::value) return \"d\";\n return nullptr;\n}\n\nenum class numeric_system {\n standard,\n // Alternative numeric system, e.g. 十二 instead of 12 in ja_JP locale.\n alternative\n};\n\n// Glibc extensions for formatting numeric values.\nenum class pad_type {\n // Pad a numeric result string with zeros (the default).\n zero,\n // Do not pad a numeric result string.\n none,\n // Pad a numeric result string with spaces.\n space,\n};\n\ntemplate \nauto write_padding(OutputIt out, pad_type pad, int width) -> OutputIt {\n if (pad == pad_type::none) return out;\n return detail::fill_n(out, width, pad == pad_type::space ? ' ' : '0');\n}\n\ntemplate \nauto write_padding(OutputIt out, pad_type pad) -> OutputIt {\n if (pad != pad_type::none) *out++ = pad == pad_type::space ? ' ' : '0';\n return out;\n}\n\n// Parses a put_time-like format string and invokes handler actions.\ntemplate \nFMT_CONSTEXPR auto parse_chrono_format(const Char* begin, const Char* end,\n Handler&& handler) -> const Char* {\n if (begin == end || *begin == '}') return begin;\n if (*begin != '%') FMT_THROW(format_error(\"invalid format\"));\n auto ptr = begin;\n while (ptr != end) {\n pad_type pad = pad_type::zero;\n auto c = *ptr;\n if (c == '}') break;\n if (c != '%') {\n ++ptr;\n continue;\n }\n if (begin != ptr) handler.on_text(begin, ptr);\n ++ptr; // consume '%'\n if (ptr == end) FMT_THROW(format_error(\"invalid format\"));\n c = *ptr;\n switch (c) {\n case '_':\n pad = pad_type::space;\n ++ptr;\n break;\n case '-':\n pad = pad_type::none;\n ++ptr;\n break;\n }\n if (ptr == end) FMT_THROW(format_error(\"invalid format\"));\n c = *ptr++;\n switch (c) {\n case '%': handler.on_text(ptr - 1, ptr); break;\n case 'n': {\n const Char newline[] = {'\\n'};\n handler.on_text(newline, newline + 1);\n break;\n }\n case 't': {\n const Char tab[] = {'\\t'};\n handler.on_text(tab, tab + 1);\n break;\n }\n // Year:\n case 'Y': handler.on_year(numeric_system::standard, pad); break;\n case 'y': handler.on_short_year(numeric_system::standard); break;\n case 'C': handler.on_century(numeric_system::standard); break;\n case 'G': handler.on_iso_week_based_year(); break;\n case 'g': handler.on_iso_week_based_short_year(); break;\n // Day of the week:\n case 'a': handler.on_abbr_weekday(); break;\n case 'A': handler.on_full_weekday(); break;\n case 'w': handler.on_dec0_weekday(numeric_system::standard); break;\n case 'u': handler.on_dec1_weekday(numeric_system::standard); break;\n // Month:\n case 'b':\n case 'h': handler.on_abbr_month(); break;\n case 'B': handler.on_full_month(); break;\n case 'm': handler.on_dec_month(numeric_system::standard, pad); break;\n // Day of the year/month:\n case 'U':\n handler.on_dec0_week_of_year(numeric_system::standard, pad);\n break;\n case 'W':\n handler.on_dec1_week_of_year(numeric_system::standard, pad);\n break;\n case 'V': handler.on_iso_week_of_year(numeric_system::standard, pad); break;\n case 'j': handler.on_day_of_year(pad); break;\n case 'd': handler.on_day_of_month(numeric_system::standard, pad); break;\n case 'e':\n handler.on_day_of_month(numeric_system::standard, pad_type::space);\n break;\n // Hour, minute, second:\n case 'H': handler.on_24_hour(numeric_system::standard, pad); break;\n case 'I': handler.on_12_hour(numeric_system::standard, pad); break;\n case 'M': handler.on_minute(numeric_system::standard, pad); break;\n case 'S': handler.on_second(numeric_system::standard, pad); break;\n // Other:\n case 'c': handler.on_datetime(numeric_system::standard); break;\n case 'x': handler.on_loc_date(numeric_system::standard); break;\n case 'X': handler.on_loc_time(numeric_system::standard); break;\n case 'D': handler.on_us_date(); break;\n case 'F': handler.on_iso_date(); break;\n case 'r': handler.on_12_hour_time(); break;\n case 'R': handler.on_24_hour_time(); break;\n case 'T': handler.on_iso_time(); break;\n case 'p': handler.on_am_pm(); break;\n case 'Q': handler.on_duration_value(); break;\n case 'q': handler.on_duration_unit(); break;\n case 'z': handler.on_utc_offset(numeric_system::standard); break;\n case 'Z': handler.on_tz_name(); break;\n // Alternative representation:\n case 'E': {\n if (ptr == end) FMT_THROW(format_error(\"invalid format\"));\n c = *ptr++;\n switch (c) {\n case 'Y': handler.on_year(numeric_system::alternative, pad); break;\n case 'y': handler.on_offset_year(); break;\n case 'C': handler.on_century(numeric_system::alternative); break;\n case 'c': handler.on_datetime(numeric_system::alternative); break;\n case 'x': handler.on_loc_date(numeric_system::alternative); break;\n case 'X': handler.on_loc_time(numeric_system::alternative); break;\n case 'z': handler.on_utc_offset(numeric_system::alternative); break;\n default: FMT_THROW(format_error(\"invalid format\"));\n }\n break;\n }\n case 'O':\n if (ptr == end) FMT_THROW(format_error(\"invalid format\"));\n c = *ptr++;\n switch (c) {\n case 'y': handler.on_short_year(numeric_system::alternative); break;\n case 'm': handler.on_dec_month(numeric_system::alternative, pad); break;\n case 'U':\n handler.on_dec0_week_of_year(numeric_system::alternative, pad);\n break;\n case 'W':\n handler.on_dec1_week_of_year(numeric_system::alternative, pad);\n break;\n case 'V':\n handler.on_iso_week_of_year(numeric_system::alternative, pad);\n break;\n case 'd':\n handler.on_day_of_month(numeric_system::alternative, pad);\n break;\n case 'e':\n handler.on_day_of_month(numeric_system::alternative, pad_type::space);\n break;\n case 'w': handler.on_dec0_weekday(numeric_system::alternative); break;\n case 'u': handler.on_dec1_weekday(numeric_system::alternative); break;\n case 'H': handler.on_24_hour(numeric_system::alternative, pad); break;\n case 'I': handler.on_12_hour(numeric_system::alternative, pad); break;\n case 'M': handler.on_minute(numeric_system::alternative, pad); break;\n case 'S': handler.on_second(numeric_system::alternative, pad); break;\n case 'z': handler.on_utc_offset(numeric_system::alternative); break;\n default: FMT_THROW(format_error(\"invalid format\"));\n }\n break;\n default: FMT_THROW(format_error(\"invalid format\"));\n }\n begin = ptr;\n }\n if (begin != ptr) handler.on_text(begin, ptr);\n return ptr;\n}\n\ntemplate struct null_chrono_spec_handler {\n FMT_CONSTEXPR void unsupported() {\n static_cast(this)->unsupported();\n }\n FMT_CONSTEXPR void on_year(numeric_system, pad_type) { unsupported(); }\n FMT_CONSTEXPR void on_short_year(numeric_system) { unsupported(); }\n FMT_CONSTEXPR void on_offset_year() { unsupported(); }\n FMT_CONSTEXPR void on_century(numeric_system) { unsupported(); }\n FMT_CONSTEXPR void on_iso_week_based_year() { unsupported(); }\n FMT_CONSTEXPR void on_iso_week_based_short_year() { unsupported(); }\n FMT_CONSTEXPR void on_abbr_weekday() { unsupported(); }\n FMT_CONSTEXPR void on_full_weekday() { unsupported(); }\n FMT_CONSTEXPR void on_dec0_weekday(numeric_system) { unsupported(); }\n FMT_CONSTEXPR void on_dec1_weekday(numeric_system) { unsupported(); }\n FMT_CONSTEXPR void on_abbr_month() { unsupported(); }\n FMT_CONSTEXPR void on_full_month() { unsupported(); }\n FMT_CONSTEXPR void on_dec_month(numeric_system, pad_type) { unsupported(); }\n FMT_CONSTEXPR void on_dec0_week_of_year(numeric_system, pad_type) {\n unsupported();\n }\n FMT_CONSTEXPR void on_dec1_week_of_year(numeric_system, pad_type) {\n unsupported();\n }\n FMT_CONSTEXPR void on_iso_week_of_year(numeric_system, pad_type) {\n unsupported();\n }\n FMT_CONSTEXPR void on_day_of_year(pad_type) { unsupported(); }\n FMT_CONSTEXPR void on_day_of_month(numeric_system, pad_type) {\n unsupported();\n }\n FMT_CONSTEXPR void on_24_hour(numeric_system) { unsupported(); }\n FMT_CONSTEXPR void on_12_hour(numeric_system) { unsupported(); }\n FMT_CONSTEXPR void on_minute(numeric_system) { unsupported(); }\n FMT_CONSTEXPR void on_second(numeric_system) { unsupported(); }\n FMT_CONSTEXPR void on_datetime(numeric_system) { unsupported(); }\n FMT_CONSTEXPR void on_loc_date(numeric_system) { unsupported(); }\n FMT_CONSTEXPR void on_loc_time(numeric_system) { unsupported(); }\n FMT_CONSTEXPR void on_us_date() { unsupported(); }\n FMT_CONSTEXPR void on_iso_date() { unsupported(); }\n FMT_CONSTEXPR void on_12_hour_time() { unsupported(); }\n FMT_CONSTEXPR void on_24_hour_time() { unsupported(); }\n FMT_CONSTEXPR void on_iso_time() { unsupported(); }\n FMT_CONSTEXPR void on_am_pm() { unsupported(); }\n FMT_CONSTEXPR void on_duration_value() { unsupported(); }\n FMT_CONSTEXPR void on_duration_unit() { unsupported(); }\n FMT_CONSTEXPR void on_utc_offset(numeric_system) { unsupported(); }\n FMT_CONSTEXPR void on_tz_name() { unsupported(); }\n};\n\nclass tm_format_checker : public null_chrono_spec_handler {\n private:\n bool has_timezone_ = false;\n\n public:\n constexpr explicit tm_format_checker(bool has_timezone)\n : has_timezone_(has_timezone) {}\n\n FMT_NORETURN inline void unsupported() {\n FMT_THROW(format_error(\"no format\"));\n }\n\n template \n FMT_CONSTEXPR void on_text(const Char*, const Char*) {}\n FMT_CONSTEXPR void on_year(numeric_system, pad_type) {}\n FMT_CONSTEXPR void on_short_year(numeric_system) {}\n FMT_CONSTEXPR void on_offset_year() {}\n FMT_CONSTEXPR void on_century(numeric_system) {}\n FMT_CONSTEXPR void on_iso_week_based_year() {}\n FMT_CONSTEXPR void on_iso_week_based_short_year() {}\n FMT_CONSTEXPR void on_abbr_weekday() {}\n FMT_CONSTEXPR void on_full_weekday() {}\n FMT_CONSTEXPR void on_dec0_weekday(numeric_system) {}\n FMT_CONSTEXPR void on_dec1_weekday(numeric_system) {}\n FMT_CONSTEXPR void on_abbr_month() {}\n FMT_CONSTEXPR void on_full_month() {}\n FMT_CONSTEXPR void on_dec_month(numeric_system, pad_type) {}\n FMT_CONSTEXPR void on_dec0_week_of_year(numeric_system, pad_type) {}\n FMT_CONSTEXPR void on_dec1_week_of_year(numeric_system, pad_type) {}\n FMT_CONSTEXPR void on_iso_week_of_year(numeric_system, pad_type) {}\n FMT_CONSTEXPR void on_day_of_year(pad_type) {}\n FMT_CONSTEXPR void on_day_of_month(numeric_system, pad_type) {}\n FMT_CONSTEXPR void on_24_hour(numeric_system, pad_type) {}\n FMT_CONSTEXPR void on_12_hour(numeric_system, pad_type) {}\n FMT_CONSTEXPR void on_minute(numeric_system, pad_type) {}\n FMT_CONSTEXPR void on_second(numeric_system, pad_type) {}\n FMT_CONSTEXPR void on_datetime(numeric_system) {}\n FMT_CONSTEXPR void on_loc_date(numeric_system) {}\n FMT_CONSTEXPR void on_loc_time(numeric_system) {}\n FMT_CONSTEXPR void on_us_date() {}\n FMT_CONSTEXPR void on_iso_date() {}\n FMT_CONSTEXPR void on_12_hour_time() {}\n FMT_CONSTEXPR void on_24_hour_time() {}\n FMT_CONSTEXPR void on_iso_time() {}\n FMT_CONSTEXPR void on_am_pm() {}\n FMT_CONSTEXPR void on_utc_offset(numeric_system) {\n if (!has_timezone_) FMT_THROW(format_error(\"no timezone\"));\n }\n FMT_CONSTEXPR void on_tz_name() {\n if (!has_timezone_) FMT_THROW(format_error(\"no timezone\"));\n }\n};\n\ninline auto tm_wday_full_name(int wday) -> const char* {\n static constexpr const char* full_name_list[] = {\n \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\n \"Thursday\", \"Friday\", \"Saturday\"};\n return wday >= 0 && wday <= 6 ? full_name_list[wday] : \"?\";\n}\ninline auto tm_wday_short_name(int wday) -> const char* {\n static constexpr const char* short_name_list[] = {\"Sun\", \"Mon\", \"Tue\", \"Wed\",\n \"Thu\", \"Fri\", \"Sat\"};\n return wday >= 0 && wday <= 6 ? short_name_list[wday] : \"???\";\n}\n\ninline auto tm_mon_full_name(int mon) -> const char* {\n static constexpr const char* full_name_list[] = {\n \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"};\n return mon >= 0 && mon <= 11 ? full_name_list[mon] : \"?\";\n}\ninline auto tm_mon_short_name(int mon) -> const char* {\n static constexpr const char* short_name_list[] = {\n \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\",\n \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\",\n };\n return mon >= 0 && mon <= 11 ? short_name_list[mon] : \"???\";\n}\n\ntemplate \nstruct has_tm_gmtoff : std::false_type {};\ntemplate \nstruct has_tm_gmtoff> : std::true_type {};\n\ntemplate struct has_tm_zone : std::false_type {};\ntemplate \nstruct has_tm_zone> : std::true_type {};\n\ntemplate ::value)>\nauto set_tm_zone(T& time, char* tz) -> bool {\n time.tm_zone = tz;\n return true;\n}\ntemplate ::value)>\nauto set_tm_zone(T&, char*) -> bool {\n return false;\n}\n\ninline auto utc() -> char* {\n static char tz[] = \"UTC\";\n return tz;\n}\n\n// Converts value to Int and checks that it's in the range [0, upper).\ntemplate ::value)>\ninline auto to_nonnegative_int(T value, Int upper) -> Int {\n if (!std::is_unsigned::value &&\n (value < 0 || to_unsigned(value) > to_unsigned(upper))) {\n FMT_THROW(format_error(\"chrono value is out of range\"));\n }\n return static_cast(value);\n}\ntemplate ::value)>\ninline auto to_nonnegative_int(T value, Int upper) -> Int {\n if (value < 0 || value >= static_cast(upper) + 1)\n FMT_THROW(format_error(\"invalid value\"));\n return static_cast(value);\n}\n\nconstexpr auto pow10(std::uint32_t n) -> long long {\n return n == 0 ? 1 : 10 * pow10(n - 1);\n}\n\n// Counts the number of fractional digits in the range [0, 18] according to the\n// C++20 spec. If more than 18 fractional digits are required then returns 6 for\n// microseconds precision.\ntemplate () / 10)>\nstruct count_fractional_digits {\n static constexpr int value =\n Num % Den == 0 ? N : count_fractional_digits::value;\n};\n\n// Base case that doesn't instantiate any more templates\n// in order to avoid overflow.\ntemplate \nstruct count_fractional_digits {\n static constexpr int value = (Num % Den == 0) ? N : 6;\n};\n\n// Format subseconds which are given as an integer type with an appropriate\n// number of digits.\ntemplate \nvoid write_fractional_seconds(OutputIt& out, Duration d, int precision = -1) {\n constexpr auto num_fractional_digits =\n count_fractional_digits::value;\n\n using subsecond_precision = std::chrono::duration<\n typename std::common_type::type,\n std::ratio<1, pow10(num_fractional_digits)>>;\n\n const auto fractional = d - detail::duration_cast(d);\n const auto subseconds =\n std::chrono::treat_as_floating_point<\n typename subsecond_precision::rep>::value\n ? fractional.count()\n : detail::duration_cast(fractional).count();\n auto n = static_cast>(subseconds);\n const int num_digits = count_digits(n);\n\n int leading_zeroes = (std::max)(0, num_fractional_digits - num_digits);\n if (precision < 0) {\n FMT_ASSERT(!std::is_floating_point::value, \"\");\n if (std::ratio_less::value) {\n *out++ = '.';\n out = detail::fill_n(out, leading_zeroes, '0');\n out = format_decimal(out, n, num_digits);\n }\n } else if (precision > 0) {\n *out++ = '.';\n leading_zeroes = min_of(leading_zeroes, precision);\n int remaining = precision - leading_zeroes;\n out = detail::fill_n(out, leading_zeroes, '0');\n if (remaining < num_digits) {\n int num_truncated_digits = num_digits - remaining;\n n /= to_unsigned(pow10(to_unsigned(num_truncated_digits)));\n if (n != 0) out = format_decimal(out, n, remaining);\n return;\n }\n if (n != 0) {\n out = format_decimal(out, n, num_digits);\n remaining -= num_digits;\n }\n out = detail::fill_n(out, remaining, '0');\n }\n}\n\n// Format subseconds which are given as a floating point type with an\n// appropriate number of digits. We cannot pass the Duration here, as we\n// explicitly need to pass the Rep value in the duration_formatter.\ntemplate \nvoid write_floating_seconds(memory_buffer& buf, Duration duration,\n int num_fractional_digits = -1) {\n using rep = typename Duration::rep;\n FMT_ASSERT(std::is_floating_point::value, \"\");\n\n auto val = duration.count();\n\n if (num_fractional_digits < 0) {\n // For `std::round` with fallback to `round`:\n // On some toolchains `std::round` is not available (e.g. GCC 6).\n using namespace std;\n num_fractional_digits =\n count_fractional_digits::value;\n if (num_fractional_digits < 6 && static_cast(round(val)) != val)\n num_fractional_digits = 6;\n }\n\n fmt::format_to(std::back_inserter(buf), FMT_STRING(\"{:.{}f}\"),\n std::fmod(val * static_cast(Duration::period::num) /\n static_cast(Duration::period::den),\n static_cast(60)),\n num_fractional_digits);\n}\n\ntemplate \nclass tm_writer {\n private:\n static constexpr int days_per_week = 7;\n\n const std::locale& loc_;\n bool is_classic_;\n OutputIt out_;\n const Duration* subsecs_;\n const std::tm& tm_;\n\n auto tm_sec() const noexcept -> int {\n FMT_ASSERT(tm_.tm_sec >= 0 && tm_.tm_sec <= 61, \"\");\n return tm_.tm_sec;\n }\n auto tm_min() const noexcept -> int {\n FMT_ASSERT(tm_.tm_min >= 0 && tm_.tm_min <= 59, \"\");\n return tm_.tm_min;\n }\n auto tm_hour() const noexcept -> int {\n FMT_ASSERT(tm_.tm_hour >= 0 && tm_.tm_hour <= 23, \"\");\n return tm_.tm_hour;\n }\n auto tm_mday() const noexcept -> int {\n FMT_ASSERT(tm_.tm_mday >= 1 && tm_.tm_mday <= 31, \"\");\n return tm_.tm_mday;\n }\n auto tm_mon() const noexcept -> int {\n FMT_ASSERT(tm_.tm_mon >= 0 && tm_.tm_mon <= 11, \"\");\n return tm_.tm_mon;\n }\n auto tm_year() const noexcept -> long long { return 1900ll + tm_.tm_year; }\n auto tm_wday() const noexcept -> int {\n FMT_ASSERT(tm_.tm_wday >= 0 && tm_.tm_wday <= 6, \"\");\n return tm_.tm_wday;\n }\n auto tm_yday() const noexcept -> int {\n FMT_ASSERT(tm_.tm_yday >= 0 && tm_.tm_yday <= 365, \"\");\n return tm_.tm_yday;\n }\n\n auto tm_hour12() const noexcept -> int {\n auto h = tm_hour();\n auto z = h < 12 ? h : h - 12;\n return z == 0 ? 12 : z;\n }\n\n // POSIX and the C Standard are unclear or inconsistent about what %C and %y\n // do if the year is negative or exceeds 9999. Use the convention that %C\n // concatenated with %y yields the same output as %Y, and that %Y contains at\n // least 4 characters, with more only if necessary.\n auto split_year_lower(long long year) const noexcept -> int {\n auto l = year % 100;\n if (l < 0) l = -l; // l in [0, 99]\n return static_cast(l);\n }\n\n // Algorithm: https://en.wikipedia.org/wiki/ISO_week_date.\n auto iso_year_weeks(long long curr_year) const noexcept -> int {\n auto prev_year = curr_year - 1;\n auto curr_p =\n (curr_year + curr_year / 4 - curr_year / 100 + curr_year / 400) %\n days_per_week;\n auto prev_p =\n (prev_year + prev_year / 4 - prev_year / 100 + prev_year / 400) %\n days_per_week;\n return 52 + ((curr_p == 4 || prev_p == 3) ? 1 : 0);\n }\n auto iso_week_num(int tm_yday, int tm_wday) const noexcept -> int {\n return (tm_yday + 11 - (tm_wday == 0 ? days_per_week : tm_wday)) /\n days_per_week;\n }\n auto tm_iso_week_year() const noexcept -> long long {\n auto year = tm_year();\n auto w = iso_week_num(tm_yday(), tm_wday());\n if (w < 1) return year - 1;\n if (w > iso_year_weeks(year)) return year + 1;\n return year;\n }\n auto tm_iso_week_of_year() const noexcept -> int {\n auto year = tm_year();\n auto w = iso_week_num(tm_yday(), tm_wday());\n if (w < 1) return iso_year_weeks(year - 1);\n if (w > iso_year_weeks(year)) return 1;\n return w;\n }\n\n void write1(int value) {\n *out_++ = static_cast('0' + to_unsigned(value) % 10);\n }\n void write2(int value) {\n const char* d = digits2(to_unsigned(value) % 100);\n *out_++ = *d++;\n *out_++ = *d;\n }\n void write2(int value, pad_type pad) {\n unsigned int v = to_unsigned(value) % 100;\n if (v >= 10) {\n const char* d = digits2(v);\n *out_++ = *d++;\n *out_++ = *d;\n } else {\n out_ = detail::write_padding(out_, pad);\n *out_++ = static_cast('0' + v);\n }\n }\n\n void write_year_extended(long long year, pad_type pad) {\n // At least 4 characters.\n int width = 4;\n bool negative = year < 0;\n if (negative) {\n year = 0 - year;\n --width;\n }\n uint32_or_64_or_128_t n = to_unsigned(year);\n const int num_digits = count_digits(n);\n if (negative && pad == pad_type::zero) *out_++ = '-';\n if (width > num_digits)\n out_ = detail::write_padding(out_, pad, width - num_digits);\n if (negative && pad != pad_type::zero) *out_++ = '-';\n out_ = format_decimal(out_, n, num_digits);\n }\n void write_year(long long year, pad_type pad) {\n write_year_extended(year, pad);\n }\n\n void write_utc_offset(long long offset, numeric_system ns) {\n if (offset < 0) {\n *out_++ = '-';\n offset = -offset;\n } else {\n *out_++ = '+';\n }\n offset /= 60;\n write2(static_cast(offset / 60));\n if (ns != numeric_system::standard) *out_++ = ':';\n write2(static_cast(offset % 60));\n }\n\n template ::value)>\n void format_utc_offset(const T& tm, numeric_system ns) {\n write_utc_offset(tm.tm_gmtoff, ns);\n }\n template ::value)>\n void format_utc_offset(const T&, numeric_system ns) {\n write_utc_offset(0, ns);\n }\n\n template ::value)>\n void format_tz_name(const T& tm) {\n if (!tm.tm_zone) FMT_THROW(format_error(\"no timezone\"));\n out_ = write_tm_str(out_, tm.tm_zone, loc_);\n }\n template ::value)>\n void format_tz_name(const T&) {\n out_ = std::copy_n(utc(), 3, out_);\n }\n\n void format_localized(char format, char modifier = 0) {\n out_ = write(out_, tm_, loc_, format, modifier);\n }\n\n public:\n tm_writer(const std::locale& loc, OutputIt out, const std::tm& tm,\n const Duration* subsecs = nullptr)\n : loc_(loc),\n is_classic_(loc_ == get_classic_locale()),\n out_(out),\n subsecs_(subsecs),\n tm_(tm) {}\n\n auto out() const -> OutputIt { return out_; }\n\n FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) {\n out_ = copy(begin, end, out_);\n }\n\n void on_abbr_weekday() {\n if (is_classic_)\n out_ = write(out_, tm_wday_short_name(tm_wday()));\n else\n format_localized('a');\n }\n void on_full_weekday() {\n if (is_classic_)\n out_ = write(out_, tm_wday_full_name(tm_wday()));\n else\n format_localized('A');\n }\n void on_dec0_weekday(numeric_system ns) {\n if (is_classic_ || ns == numeric_system::standard) return write1(tm_wday());\n format_localized('w', 'O');\n }\n void on_dec1_weekday(numeric_system ns) {\n if (is_classic_ || ns == numeric_system::standard) {\n auto wday = tm_wday();\n write1(wday == 0 ? days_per_week : wday);\n } else {\n format_localized('u', 'O');\n }\n }\n\n void on_abbr_month() {\n if (is_classic_)\n out_ = write(out_, tm_mon_short_name(tm_mon()));\n else\n format_localized('b');\n }\n void on_full_month() {\n if (is_classic_)\n out_ = write(out_, tm_mon_full_name(tm_mon()));\n else\n format_localized('B');\n }\n\n void on_datetime(numeric_system ns) {\n if (is_classic_) {\n on_abbr_weekday();\n *out_++ = ' ';\n on_abbr_month();\n *out_++ = ' ';\n on_day_of_month(numeric_system::standard, pad_type::space);\n *out_++ = ' ';\n on_iso_time();\n *out_++ = ' ';\n on_year(numeric_system::standard, pad_type::space);\n } else {\n format_localized('c', ns == numeric_system::standard ? '\\0' : 'E');\n }\n }\n void on_loc_date(numeric_system ns) {\n if (is_classic_)\n on_us_date();\n else\n format_localized('x', ns == numeric_system::standard ? '\\0' : 'E');\n }\n void on_loc_time(numeric_system ns) {\n if (is_classic_)\n on_iso_time();\n else\n format_localized('X', ns == numeric_system::standard ? '\\0' : 'E');\n }\n void on_us_date() {\n char buf[8];\n write_digit2_separated(buf, to_unsigned(tm_mon() + 1),\n to_unsigned(tm_mday()),\n to_unsigned(split_year_lower(tm_year())), '/');\n out_ = copy(std::begin(buf), std::end(buf), out_);\n }\n void on_iso_date() {\n auto year = tm_year();\n char buf[10];\n size_t offset = 0;\n if (year >= 0 && year < 10000) {\n write2digits(buf, static_cast(year / 100));\n } else {\n offset = 4;\n write_year_extended(year, pad_type::zero);\n year = 0;\n }\n write_digit2_separated(buf + 2, static_cast(year % 100),\n to_unsigned(tm_mon() + 1), to_unsigned(tm_mday()),\n '-');\n out_ = copy(std::begin(buf) + offset, std::end(buf), out_);\n }\n\n void on_utc_offset(numeric_system ns) { format_utc_offset(tm_, ns); }\n void on_tz_name() { format_tz_name(tm_); }\n\n void on_year(numeric_system ns, pad_type pad) {\n if (is_classic_ || ns == numeric_system::standard)\n return write_year(tm_year(), pad);\n format_localized('Y', 'E');\n }\n void on_short_year(numeric_system ns) {\n if (is_classic_ || ns == numeric_system::standard)\n return write2(split_year_lower(tm_year()));\n format_localized('y', 'O');\n }\n void on_offset_year() {\n if (is_classic_) return write2(split_year_lower(tm_year()));\n format_localized('y', 'E');\n }\n\n void on_century(numeric_system ns) {\n if (is_classic_ || ns == numeric_system::standard) {\n auto year = tm_year();\n auto upper = year / 100;\n if (year >= -99 && year < 0) {\n // Zero upper on negative year.\n *out_++ = '-';\n *out_++ = '0';\n } else if (upper >= 0 && upper < 100) {\n write2(static_cast(upper));\n } else {\n out_ = write(out_, upper);\n }\n } else {\n format_localized('C', 'E');\n }\n }\n\n void on_dec_month(numeric_system ns, pad_type pad) {\n if (is_classic_ || ns == numeric_system::standard)\n return write2(tm_mon() + 1, pad);\n format_localized('m', 'O');\n }\n\n void on_dec0_week_of_year(numeric_system ns, pad_type pad) {\n if (is_classic_ || ns == numeric_system::standard)\n return write2((tm_yday() + days_per_week - tm_wday()) / days_per_week,\n pad);\n format_localized('U', 'O');\n }\n void on_dec1_week_of_year(numeric_system ns, pad_type pad) {\n if (is_classic_ || ns == numeric_system::standard) {\n auto wday = tm_wday();\n write2((tm_yday() + days_per_week -\n (wday == 0 ? (days_per_week - 1) : (wday - 1))) /\n days_per_week,\n pad);\n } else {\n format_localized('W', 'O');\n }\n }\n void on_iso_week_of_year(numeric_system ns, pad_type pad) {\n if (is_classic_ || ns == numeric_system::standard)\n return write2(tm_iso_week_of_year(), pad);\n format_localized('V', 'O');\n }\n\n void on_iso_week_based_year() {\n write_year(tm_iso_week_year(), pad_type::zero);\n }\n void on_iso_week_based_short_year() {\n write2(split_year_lower(tm_iso_week_year()));\n }\n\n void on_day_of_year(pad_type pad) {\n auto yday = tm_yday() + 1;\n auto digit1 = yday / 100;\n if (digit1 != 0)\n write1(digit1);\n else\n out_ = detail::write_padding(out_, pad);\n write2(yday % 100, pad);\n }\n\n void on_day_of_month(numeric_system ns, pad_type pad) {\n if (is_classic_ || ns == numeric_system::standard)\n return write2(tm_mday(), pad);\n format_localized('d', 'O');\n }\n\n void on_24_hour(numeric_system ns, pad_type pad) {\n if (is_classic_ || ns == numeric_system::standard)\n return write2(tm_hour(), pad);\n format_localized('H', 'O');\n }\n void on_12_hour(numeric_system ns, pad_type pad) {\n if (is_classic_ || ns == numeric_system::standard)\n return write2(tm_hour12(), pad);\n format_localized('I', 'O');\n }\n void on_minute(numeric_system ns, pad_type pad) {\n if (is_classic_ || ns == numeric_system::standard)\n return write2(tm_min(), pad);\n format_localized('M', 'O');\n }\n\n void on_second(numeric_system ns, pad_type pad) {\n if (is_classic_ || ns == numeric_system::standard) {\n write2(tm_sec(), pad);\n if (subsecs_) {\n if (std::is_floating_point::value) {\n auto buf = memory_buffer();\n write_floating_seconds(buf, *subsecs_);\n if (buf.size() > 1) {\n // Remove the leading \"0\", write something like \".123\".\n out_ = copy(buf.begin() + 1, buf.end(), out_);\n }\n } else {\n write_fractional_seconds(out_, *subsecs_);\n }\n }\n } else {\n // Currently no formatting of subseconds when a locale is set.\n format_localized('S', 'O');\n }\n }\n\n void on_12_hour_time() {\n if (is_classic_) {\n char buf[8];\n write_digit2_separated(buf, to_unsigned(tm_hour12()),\n to_unsigned(tm_min()), to_unsigned(tm_sec()), ':');\n out_ = copy(std::begin(buf), std::end(buf), out_);\n *out_++ = ' ';\n on_am_pm();\n } else {\n format_localized('r');\n }\n }\n void on_24_hour_time() {\n write2(tm_hour());\n *out_++ = ':';\n write2(tm_min());\n }\n void on_iso_time() {\n on_24_hour_time();\n *out_++ = ':';\n on_second(numeric_system::standard, pad_type::zero);\n }\n\n void on_am_pm() {\n if (is_classic_) {\n *out_++ = tm_hour() < 12 ? 'A' : 'P';\n *out_++ = 'M';\n } else {\n format_localized('p');\n }\n }\n\n // These apply to chrono durations but not tm.\n void on_duration_value() {}\n void on_duration_unit() {}\n};\n\nstruct chrono_format_checker : null_chrono_spec_handler {\n bool has_precision_integral = false;\n\n FMT_NORETURN inline void unsupported() { FMT_THROW(format_error(\"no date\")); }\n\n template \n FMT_CONSTEXPR void on_text(const Char*, const Char*) {}\n FMT_CONSTEXPR void on_day_of_year(pad_type) {}\n FMT_CONSTEXPR void on_24_hour(numeric_system, pad_type) {}\n FMT_CONSTEXPR void on_12_hour(numeric_system, pad_type) {}\n FMT_CONSTEXPR void on_minute(numeric_system, pad_type) {}\n FMT_CONSTEXPR void on_second(numeric_system, pad_type) {}\n FMT_CONSTEXPR void on_12_hour_time() {}\n FMT_CONSTEXPR void on_24_hour_time() {}\n FMT_CONSTEXPR void on_iso_time() {}\n FMT_CONSTEXPR void on_am_pm() {}\n FMT_CONSTEXPR void on_duration_value() const {\n if (has_precision_integral)\n FMT_THROW(format_error(\"precision not allowed for this argument type\"));\n }\n FMT_CONSTEXPR void on_duration_unit() {}\n};\n\ntemplate ::value&& has_isfinite::value)>\ninline auto isfinite(T) -> bool {\n return true;\n}\n\ntemplate ::value)>\ninline auto mod(T x, int y) -> T {\n return x % static_cast(y);\n}\ntemplate ::value)>\ninline auto mod(T x, int y) -> T {\n return std::fmod(x, static_cast(y));\n}\n\n// If T is an integral type, maps T to its unsigned counterpart, otherwise\n// leaves it unchanged (unlike std::make_unsigned).\ntemplate ::value>\nstruct make_unsigned_or_unchanged {\n using type = T;\n};\n\ntemplate struct make_unsigned_or_unchanged {\n using type = typename std::make_unsigned::type;\n};\n\ntemplate ::value)>\ninline auto get_milliseconds(std::chrono::duration d)\n -> std::chrono::duration {\n // This may overflow and/or the result may not fit in the target type.\n#if FMT_SAFE_DURATION_CAST\n using common_seconds_type =\n typename std::common_type::type;\n auto d_as_common = detail::duration_cast(d);\n auto d_as_whole_seconds =\n detail::duration_cast(d_as_common);\n // This conversion should be nonproblematic.\n auto diff = d_as_common - d_as_whole_seconds;\n auto ms = detail::duration_cast>(diff);\n return ms;\n#else\n auto s = detail::duration_cast(d);\n return detail::duration_cast(d - s);\n#endif\n}\n\ntemplate ::value)>\nauto format_duration_value(OutputIt out, Rep val, int) -> OutputIt {\n return write(out, val);\n}\n\ntemplate ::value)>\nauto format_duration_value(OutputIt out, Rep val, int precision) -> OutputIt {\n auto specs = format_specs();\n specs.precision = precision;\n specs.set_type(precision >= 0 ? presentation_type::fixed\n : presentation_type::general);\n return write(out, val, specs);\n}\n\ntemplate \nauto copy_unit(string_view unit, OutputIt out, Char) -> OutputIt {\n return copy(unit.begin(), unit.end(), out);\n}\n\ntemplate \nauto copy_unit(string_view unit, OutputIt out, wchar_t) -> OutputIt {\n // This works when wchar_t is UTF-32 because units only contain characters\n // that have the same representation in UTF-16 and UTF-32.\n utf8_to_utf16 u(unit);\n return copy(u.c_str(), u.c_str() + u.size(), out);\n}\n\ntemplate \nauto format_duration_unit(OutputIt out) -> OutputIt {\n if (const char* unit = get_units())\n return copy_unit(string_view(unit), out, Char());\n *out++ = '[';\n out = write(out, Period::num);\n if FMT_CONSTEXPR20 (Period::den != 1) {\n *out++ = '/';\n out = write(out, Period::den);\n }\n *out++ = ']';\n *out++ = 's';\n return out;\n}\n\nclass get_locale {\n private:\n union {\n std::locale locale_;\n };\n bool has_locale_ = false;\n\n public:\n inline get_locale(bool localized, locale_ref loc) : has_locale_(localized) {\n if (!localized) return;\n ignore_unused(loc);\n ::new (&locale_) std::locale(\n#if FMT_USE_LOCALE\n loc.template get()\n#endif\n );\n }\n inline ~get_locale() {\n if (has_locale_) locale_.~locale();\n }\n inline operator const std::locale&() const {\n return has_locale_ ? locale_ : get_classic_locale();\n }\n};\n\ntemplate \nstruct duration_formatter {\n using iterator = basic_appender;\n iterator out;\n // rep is unsigned to avoid overflow.\n using rep =\n conditional_t::value && sizeof(Rep) < sizeof(int),\n unsigned, typename make_unsigned_or_unchanged::type>;\n rep val;\n int precision;\n locale_ref locale;\n bool localized = false;\n using seconds = std::chrono::duration;\n seconds s;\n using milliseconds = std::chrono::duration;\n bool negative;\n\n using tm_writer_type = tm_writer;\n\n duration_formatter(iterator o, std::chrono::duration d,\n locale_ref loc)\n : out(o), val(static_cast(d.count())), locale(loc), negative(false) {\n if (d.count() < 0) {\n val = 0 - val;\n negative = true;\n }\n\n // this may overflow and/or the result may not fit in the\n // target type.\n // might need checked conversion (rep!=Rep)\n s = detail::duration_cast(std::chrono::duration(val));\n }\n\n // returns true if nan or inf, writes to out.\n auto handle_nan_inf() -> bool {\n if (isfinite(val)) return false;\n if (isnan(val)) {\n write_nan();\n return true;\n }\n // must be +-inf\n if (val > 0)\n std::copy_n(\"inf\", 3, out);\n else\n std::copy_n(\"-inf\", 4, out);\n return true;\n }\n\n auto days() const -> Rep { return static_cast(s.count() / 86400); }\n auto hour() const -> Rep {\n return static_cast(mod((s.count() / 3600), 24));\n }\n\n auto hour12() const -> Rep {\n Rep hour = static_cast(mod((s.count() / 3600), 12));\n return hour <= 0 ? 12 : hour;\n }\n\n auto minute() const -> Rep {\n return static_cast(mod((s.count() / 60), 60));\n }\n auto second() const -> Rep { return static_cast(mod(s.count(), 60)); }\n\n auto time() const -> std::tm {\n auto time = std::tm();\n time.tm_hour = to_nonnegative_int(hour(), 24);\n time.tm_min = to_nonnegative_int(minute(), 60);\n time.tm_sec = to_nonnegative_int(second(), 60);\n return time;\n }\n\n void write_sign() {\n if (!negative) return;\n *out++ = '-';\n negative = false;\n }\n\n void write(Rep value, int width, pad_type pad = pad_type::zero) {\n write_sign();\n if (isnan(value)) return write_nan();\n uint32_or_64_or_128_t n =\n to_unsigned(to_nonnegative_int(value, max_value()));\n int num_digits = detail::count_digits(n);\n if (width > num_digits) {\n out = detail::write_padding(out, pad, width - num_digits);\n }\n out = format_decimal(out, n, num_digits);\n }\n\n void write_nan() { std::copy_n(\"nan\", 3, out); }\n\n template \n void format_tm(const tm& time, Callback cb, Args... args) {\n if (isnan(val)) return write_nan();\n get_locale loc(localized, locale);\n auto w = tm_writer_type(loc, out, time);\n (w.*cb)(args...);\n out = w.out();\n }\n\n void on_text(const Char* begin, const Char* end) {\n copy(begin, end, out);\n }\n\n // These are not implemented because durations don't have date information.\n void on_abbr_weekday() {}\n void on_full_weekday() {}\n void on_dec0_weekday(numeric_system) {}\n void on_dec1_weekday(numeric_system) {}\n void on_abbr_month() {}\n void on_full_month() {}\n void on_datetime(numeric_system) {}\n void on_loc_date(numeric_system) {}\n void on_loc_time(numeric_system) {}\n void on_us_date() {}\n void on_iso_date() {}\n void on_utc_offset(numeric_system) {}\n void on_tz_name() {}\n void on_year(numeric_system, pad_type) {}\n void on_short_year(numeric_system) {}\n void on_offset_year() {}\n void on_century(numeric_system) {}\n void on_iso_week_based_year() {}\n void on_iso_week_based_short_year() {}\n void on_dec_month(numeric_system, pad_type) {}\n void on_dec0_week_of_year(numeric_system, pad_type) {}\n void on_dec1_week_of_year(numeric_system, pad_type) {}\n void on_iso_week_of_year(numeric_system, pad_type) {}\n void on_day_of_month(numeric_system, pad_type) {}\n\n void on_day_of_year(pad_type) {\n if (handle_nan_inf()) return;\n write(days(), 0);\n }\n\n void on_24_hour(numeric_system ns, pad_type pad) {\n if (handle_nan_inf()) return;\n\n if (ns == numeric_system::standard) return write(hour(), 2, pad);\n auto time = tm();\n time.tm_hour = to_nonnegative_int(hour(), 24);\n format_tm(time, &tm_writer_type::on_24_hour, ns, pad);\n }\n\n void on_12_hour(numeric_system ns, pad_type pad) {\n if (handle_nan_inf()) return;\n\n if (ns == numeric_system::standard) return write(hour12(), 2, pad);\n auto time = tm();\n time.tm_hour = to_nonnegative_int(hour12(), 12);\n format_tm(time, &tm_writer_type::on_12_hour, ns, pad);\n }\n\n void on_minute(numeric_system ns, pad_type pad) {\n if (handle_nan_inf()) return;\n\n if (ns == numeric_system::standard) return write(minute(), 2, pad);\n auto time = tm();\n time.tm_min = to_nonnegative_int(minute(), 60);\n format_tm(time, &tm_writer_type::on_minute, ns, pad);\n }\n\n void on_second(numeric_system ns, pad_type pad) {\n if (handle_nan_inf()) return;\n\n if (ns == numeric_system::standard) {\n if (std::is_floating_point::value) {\n auto buf = memory_buffer();\n write_floating_seconds(buf, std::chrono::duration(val),\n precision);\n if (negative) *out++ = '-';\n if (buf.size() < 2 || buf[1] == '.')\n out = detail::write_padding(out, pad);\n out = copy(buf.begin(), buf.end(), out);\n } else {\n write(second(), 2, pad);\n write_fractional_seconds(\n out, std::chrono::duration(val), precision);\n }\n return;\n }\n auto time = tm();\n time.tm_sec = to_nonnegative_int(second(), 60);\n format_tm(time, &tm_writer_type::on_second, ns, pad);\n }\n\n void on_12_hour_time() {\n if (handle_nan_inf()) return;\n format_tm(time(), &tm_writer_type::on_12_hour_time);\n }\n\n void on_24_hour_time() {\n if (handle_nan_inf()) {\n *out++ = ':';\n handle_nan_inf();\n return;\n }\n\n write(hour(), 2);\n *out++ = ':';\n write(minute(), 2);\n }\n\n void on_iso_time() {\n on_24_hour_time();\n *out++ = ':';\n if (handle_nan_inf()) return;\n on_second(numeric_system::standard, pad_type::zero);\n }\n\n void on_am_pm() {\n if (handle_nan_inf()) return;\n format_tm(time(), &tm_writer_type::on_am_pm);\n }\n\n void on_duration_value() {\n if (handle_nan_inf()) return;\n write_sign();\n out = format_duration_value(out, val, precision);\n }\n\n void on_duration_unit() { out = format_duration_unit(out); }\n};\n\n} // namespace detail\n\n#if defined(__cpp_lib_chrono) && __cpp_lib_chrono >= 201907\nusing weekday = std::chrono::weekday;\nusing day = std::chrono::day;\nusing month = std::chrono::month;\nusing year = std::chrono::year;\nusing year_month_day = std::chrono::year_month_day;\n#else\n// A fallback version of weekday.\nclass weekday {\n private:\n unsigned char value_;\n\n public:\n weekday() = default;\n constexpr explicit weekday(unsigned wd) noexcept\n : value_(static_cast(wd != 7 ? wd : 0)) {}\n constexpr auto c_encoding() const noexcept -> unsigned { return value_; }\n};\n\nclass day {\n private:\n unsigned char value_;\n\n public:\n day() = default;\n constexpr explicit day(unsigned d) noexcept\n : value_(static_cast(d)) {}\n constexpr explicit operator unsigned() const noexcept { return value_; }\n};\n\nclass month {\n private:\n unsigned char value_;\n\n public:\n month() = default;\n constexpr explicit month(unsigned m) noexcept\n : value_(static_cast(m)) {}\n constexpr explicit operator unsigned() const noexcept { return value_; }\n};\n\nclass year {\n private:\n int value_;\n\n public:\n year() = default;\n constexpr explicit year(int y) noexcept : value_(y) {}\n constexpr explicit operator int() const noexcept { return value_; }\n};\n\nclass year_month_day {\n private:\n fmt::year year_;\n fmt::month month_;\n fmt::day day_;\n\n public:\n year_month_day() = default;\n constexpr year_month_day(const year& y, const month& m, const day& d) noexcept\n : year_(y), month_(m), day_(d) {}\n constexpr auto year() const noexcept -> fmt::year { return year_; }\n constexpr auto month() const noexcept -> fmt::month { return month_; }\n constexpr auto day() const noexcept -> fmt::day { return day_; }\n};\n#endif // __cpp_lib_chrono >= 201907\n\ntemplate \nstruct formatter : private formatter {\n private:\n bool use_tm_formatter_ = false;\n\n public:\n FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* {\n auto it = ctx.begin(), end = ctx.end();\n if (it != end && *it == 'L') {\n ++it;\n this->set_localized();\n }\n use_tm_formatter_ = it != end && *it != '}';\n return use_tm_formatter_ ? formatter::parse(ctx) : it;\n }\n\n template \n auto format(weekday wd, FormatContext& ctx) const -> decltype(ctx.out()) {\n auto time = std::tm();\n time.tm_wday = static_cast(wd.c_encoding());\n if (use_tm_formatter_) return formatter::format(time, ctx);\n detail::get_locale loc(this->localized(), ctx.locale());\n auto w = detail::tm_writer(loc, ctx.out(), time);\n w.on_abbr_weekday();\n return w.out();\n }\n};\n\ntemplate \nstruct formatter : private formatter {\n private:\n bool use_tm_formatter_ = false;\n\n public:\n FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* {\n auto it = ctx.begin(), end = ctx.end();\n use_tm_formatter_ = it != end && *it != '}';\n return use_tm_formatter_ ? formatter::parse(ctx) : it;\n }\n\n template \n auto format(day d, FormatContext& ctx) const -> decltype(ctx.out()) {\n auto time = std::tm();\n time.tm_mday = static_cast(static_cast(d));\n if (use_tm_formatter_) return formatter::format(time, ctx);\n detail::get_locale loc(false, ctx.locale());\n auto w = detail::tm_writer(loc, ctx.out(), time);\n w.on_day_of_month(detail::numeric_system::standard, detail::pad_type::zero);\n return w.out();\n }\n};\n\ntemplate \nstruct formatter : private formatter {\n private:\n bool use_tm_formatter_ = false;\n\n public:\n FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* {\n auto it = ctx.begin(), end = ctx.end();\n if (it != end && *it == 'L') {\n ++it;\n this->set_localized();\n }\n use_tm_formatter_ = it != end && *it != '}';\n return use_tm_formatter_ ? formatter::parse(ctx) : it;\n }\n\n template \n auto format(month m, FormatContext& ctx) const -> decltype(ctx.out()) {\n auto time = std::tm();\n time.tm_mon = static_cast(static_cast(m)) - 1;\n if (use_tm_formatter_) return formatter::format(time, ctx);\n detail::get_locale loc(this->localized(), ctx.locale());\n auto w = detail::tm_writer(loc, ctx.out(), time);\n w.on_abbr_month();\n return w.out();\n }\n};\n\ntemplate \nstruct formatter : private formatter {\n private:\n bool use_tm_formatter_ = false;\n\n public:\n FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* {\n auto it = ctx.begin(), end = ctx.end();\n use_tm_formatter_ = it != end && *it != '}';\n return use_tm_formatter_ ? formatter::parse(ctx) : it;\n }\n\n template \n auto format(year y, FormatContext& ctx) const -> decltype(ctx.out()) {\n auto time = std::tm();\n time.tm_year = static_cast(y) - 1900;\n if (use_tm_formatter_) return formatter::format(time, ctx);\n detail::get_locale loc(false, ctx.locale());\n auto w = detail::tm_writer(loc, ctx.out(), time);\n w.on_year(detail::numeric_system::standard, detail::pad_type::zero);\n return w.out();\n }\n};\n\ntemplate \nstruct formatter : private formatter {\n private:\n bool use_tm_formatter_ = false;\n\n public:\n FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* {\n auto it = ctx.begin(), end = ctx.end();\n use_tm_formatter_ = it != end && *it != '}';\n return use_tm_formatter_ ? formatter::parse(ctx) : it;\n }\n\n template \n auto format(year_month_day val, FormatContext& ctx) const\n -> decltype(ctx.out()) {\n auto time = std::tm();\n time.tm_year = static_cast(val.year()) - 1900;\n time.tm_mon = static_cast(static_cast(val.month())) - 1;\n time.tm_mday = static_cast(static_cast(val.day()));\n if (use_tm_formatter_) return formatter::format(time, ctx);\n detail::get_locale loc(true, ctx.locale());\n auto w = detail::tm_writer(loc, ctx.out(), time);\n w.on_iso_date();\n return w.out();\n }\n};\n\ntemplate \nstruct formatter, Char> {\n private:\n format_specs specs_;\n detail::arg_ref width_ref_;\n detail::arg_ref precision_ref_;\n basic_string_view fmt_;\n\n public:\n FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* {\n auto it = ctx.begin(), end = ctx.end();\n if (it == end || *it == '}') return it;\n\n it = detail::parse_align(it, end, specs_);\n if (it == end) return it;\n\n Char c = *it;\n if ((c >= '0' && c <= '9') || c == '{') {\n it = detail::parse_width(it, end, specs_, width_ref_, ctx);\n if (it == end) return it;\n }\n\n auto checker = detail::chrono_format_checker();\n if (*it == '.') {\n checker.has_precision_integral = !std::is_floating_point::value;\n it = detail::parse_precision(it, end, specs_, precision_ref_, ctx);\n }\n if (it != end && *it == 'L') {\n specs_.set_localized();\n ++it;\n }\n end = detail::parse_chrono_format(it, end, checker);\n fmt_ = {it, detail::to_unsigned(end - it)};\n return end;\n }\n\n template \n auto format(std::chrono::duration d, FormatContext& ctx) const\n -> decltype(ctx.out()) {\n auto specs = specs_;\n auto precision = specs.precision;\n specs.precision = -1;\n auto begin = fmt_.begin(), end = fmt_.end();\n // As a possible future optimization, we could avoid extra copying if width\n // is not specified.\n auto buf = basic_memory_buffer();\n auto out = basic_appender(buf);\n detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_,\n ctx);\n detail::handle_dynamic_spec(specs.dynamic_precision(), precision,\n precision_ref_, ctx);\n if (begin == end || *begin == '}') {\n out = detail::format_duration_value(out, d.count(), precision);\n detail::format_duration_unit(out);\n } else {\n auto f =\n detail::duration_formatter(out, d, ctx.locale());\n f.precision = precision;\n f.localized = specs_.localized();\n detail::parse_chrono_format(begin, end, f);\n }\n return detail::write(\n ctx.out(), basic_string_view(buf.data(), buf.size()), specs);\n }\n};\n\ntemplate struct formatter {\n private:\n format_specs specs_;\n detail::arg_ref width_ref_;\n basic_string_view fmt_ =\n detail::string_literal();\n\n protected:\n auto localized() const -> bool { return specs_.localized(); }\n FMT_CONSTEXPR void set_localized() { specs_.set_localized(); }\n\n FMT_CONSTEXPR auto do_parse(parse_context& ctx, bool has_timezone)\n -> const Char* {\n auto it = ctx.begin(), end = ctx.end();\n if (it == end || *it == '}') return it;\n\n it = detail::parse_align(it, end, specs_);\n if (it == end) return it;\n\n Char c = *it;\n if ((c >= '0' && c <= '9') || c == '{') {\n it = detail::parse_width(it, end, specs_, width_ref_, ctx);\n if (it == end) return it;\n }\n\n if (*it == 'L') {\n specs_.set_localized();\n ++it;\n }\n\n end = detail::parse_chrono_format(it, end,\n detail::tm_format_checker(has_timezone));\n // Replace the default format string only if the new spec is not empty.\n if (end != it) fmt_ = {it, detail::to_unsigned(end - it)};\n return end;\n }\n\n template \n auto do_format(const std::tm& tm, FormatContext& ctx,\n const Duration* subsecs) const -> decltype(ctx.out()) {\n auto specs = specs_;\n auto buf = basic_memory_buffer();\n auto out = basic_appender(buf);\n detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_,\n ctx);\n\n auto loc_ref = specs.localized() ? ctx.locale() : locale_ref();\n detail::get_locale loc(static_cast(loc_ref), loc_ref);\n auto w = detail::tm_writer, Char, Duration>(\n loc, out, tm, subsecs);\n detail::parse_chrono_format(fmt_.begin(), fmt_.end(), w);\n return detail::write(\n ctx.out(), basic_string_view(buf.data(), buf.size()), specs);\n }\n\n public:\n FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* {\n return do_parse(ctx, detail::has_tm_gmtoff::value);\n }\n\n template \n auto format(const std::tm& tm, FormatContext& ctx) const\n -> decltype(ctx.out()) {\n return do_format(tm, ctx, nullptr);\n }\n};\n\n// DEPRECATED! Reversed order of template parameters.\ntemplate \nstruct formatter, Char> : private formatter {\n FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* {\n return this->do_parse(ctx, true);\n }\n\n template \n auto format(sys_time val, FormatContext& ctx) const\n -> decltype(ctx.out()) {\n std::tm tm = gmtime(val);\n using period = typename Duration::period;\n if FMT_CONSTEXPR20 (period::num == 1 && period::den == 1 &&\n !std::is_floating_point<\n typename Duration::rep>::value) {\n detail::set_tm_zone(tm, detail::utc());\n return formatter::format(tm, ctx);\n }\n Duration epoch = val.time_since_epoch();\n Duration subsecs = detail::duration_cast(\n epoch - detail::duration_cast(epoch));\n if (subsecs.count() < 0) {\n auto second = detail::duration_cast(std::chrono::seconds(1));\n if (tm.tm_sec != 0) {\n --tm.tm_sec;\n } else {\n tm = gmtime(val - second);\n detail::set_tm_zone(tm, detail::utc());\n }\n subsecs += second;\n }\n return formatter::do_format(tm, ctx, &subsecs);\n }\n};\n\ntemplate \nstruct formatter, Char>\n : formatter, Char> {\n template \n auto format(utc_time val, FormatContext& ctx) const\n -> decltype(ctx.out()) {\n return formatter, Char>::format(\n detail::utc_clock::to_sys(val), ctx);\n }\n};\n\ntemplate \nstruct formatter, Char>\n : private formatter {\n FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* {\n return this->do_parse(ctx, false);\n }\n\n template \n auto format(local_time val, FormatContext& ctx) const\n -> decltype(ctx.out()) {\n auto time_since_epoch = val.time_since_epoch();\n auto seconds_since_epoch =\n detail::duration_cast(time_since_epoch);\n // Use gmtime to prevent time zone conversion since local_time has an\n // unspecified time zone.\n std::tm t = gmtime(seconds_since_epoch.count());\n using period = typename Duration::period;\n if (period::num == 1 && period::den == 1 &&\n !std::is_floating_point::value) {\n return formatter::format(t, ctx);\n }\n auto subsecs =\n detail::duration_cast(time_since_epoch - seconds_since_epoch);\n return formatter::do_format(t, ctx, &subsecs);\n }\n};\n\nFMT_END_EXPORT\nFMT_END_NAMESPACE\n\n#endif // FMT_CHRONO_H_", "messages": null, "tools": null} {"id": "9e8261c7f99a9457", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/node/watch.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 2848, "sha256": "9c55c25b51f60eca64bf118e7152a2298db1402cb03291a6e860c4dfe0fcb392", "text": "import { EventEmitter } from 'node:events'\nimport path from 'node:path'\nimport type { OutputOptions, WatcherOptions } from 'rolldown'\nimport colors from 'picocolors'\nimport { escapePath } from 'tinyglobby'\nimport type { FSWatcher, WatchOptions } from '#dep-types/chokidar'\nimport { withTrailingSlash } from '../shared/utils'\nimport { arraify, normalizePath } from './utils'\nimport type { Logger } from './logger'\n\nexport function getResolvedOutDirs(\n root: string,\n outDir: string,\n outputOptions: OutputOptions[] | OutputOptions | undefined,\n): Set {\n const resolvedOutDir = path.resolve(root, outDir)\n if (!outputOptions) return new Set([resolvedOutDir])\n\n return new Set(\n arraify(outputOptions).map(({ dir }) =>\n dir ? path.resolve(root, dir) : resolvedOutDir,\n ),\n )\n}\n\nexport function resolveEmptyOutDir(\n emptyOutDir: boolean | null,\n root: string,\n outDirs: Set,\n logger?: Logger,\n): boolean {\n if (emptyOutDir != null) return emptyOutDir\n\n for (const outDir of outDirs) {\n if (!normalizePath(outDir).startsWith(withTrailingSlash(root))) {\n // warn if outDir is outside of root\n logger?.warn(\n colors.yellow(\n `\\n${colors.bold(`(!)`)} outDir ${colors.white(\n colors.dim(outDir),\n )} is not inside project root and will not be emptied.\\n` +\n `Use --emptyOutDir to override.\\n`,\n ),\n )\n return false\n }\n }\n return true\n}\n\nexport function resolveChokidarOptions(\n options: WatchOptions | undefined,\n resolvedOutDirs: Set,\n emptyOutDir: boolean,\n cacheDir: string,\n): WatchOptions {\n const { ignored: ignoredList, ...otherOptions } = options ?? {}\n const ignored: WatchOptions['ignored'] = [\n '**/.git/**',\n '**/node_modules/**',\n '**/test-results/**', // Playwright\n escapePath(cacheDir) + '/**',\n ...arraify(ignoredList || []),\n ]\n if (emptyOutDir) {\n ignored.push(\n ...[...resolvedOutDirs].map((outDir) => escapePath(outDir) + '/**'),\n )\n }\n\n const resolvedWatchOptions: WatchOptions = {\n ignored,\n ignoreInitial: true,\n ignorePermissionErrors: true,\n ...otherOptions,\n }\n\n return resolvedWatchOptions\n}\n\nexport function convertToWatcherOptions(\n options: WatchOptions | undefined,\n): WatcherOptions['watcher'] {\n if (!options) return\n\n return {\n usePolling: options.usePolling,\n pollInterval: options.interval,\n }\n}\n\nclass NoopWatcher extends EventEmitter implements FSWatcher {\n constructor(public options: WatchOptions) {\n super()\n }\n\n add() {\n return this\n }\n\n unwatch() {\n return this\n }\n\n getWatched() {\n return {}\n }\n\n ref() {\n return this\n }\n\n unref() {\n return this\n }\n\n async close() {\n // noop\n }\n}\n\nexport function createNoopWatcher(options: WatchOptions): FSWatcher {\n return new NoopWatcher(options)\n}", "messages": null, "tools": null} {"id": "9ec024459cece245", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/api/json_sax/end_array.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 439, "sha256": "176a51300ed44c46dd32a88b26032962bf4d8d4cc9278093acce4ce1c261d889", "text": "# nlohmann::json_sax::end_array\n\n```cpp\nvirtual bool end_array() = 0;\n```\n\nThe end of an array was read.\n\n## Return value\n\nWhether parsing should proceed.\n\n## Examples\n\n??? example\n\n The example below shows how the SAX interface is used.\n\n ```cpp\n --8<-- \"examples/sax_parse.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/sax_parse.output\"\n ```\n\n## Version history\n\n- Added in version 3.2.0.", "messages": null, "tools": null} {"id": "9ec8c3ea189fbeb3", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/module-runner/__tests_dts__/importMeta.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 811, "sha256": "1ffa067e0c4c8bf6e1f249f5828710fd3064e1faa5bb60aea24fbe9a7b4b71df", "text": "/**\n * Type test to verify ModuleRunnerImportMeta is structurally compatible\n * with ImportMeta (including @types/node augmentations).\n *\n * This replaces `extends ImportMeta` in the interface declaration with a\n * test-only assignability check that won't cause TS2717 \"subsequent property\n * declarations must have the same type\" errors in consumer projects using\n * skipLibCheck: false with augmented ImportMeta.\n */\n\nimport type { ExpectExtends, ExpectTrue } from '@type-challenges/utils'\nimport type { ModuleRunnerImportMeta } from '../types'\n\nexport type cases = [\n // Ensure ModuleRunnerImportMeta is assignable to ImportMeta\n // (which includes @types/node augmentations: dirname, filename, url, resolve, main)\n ExpectTrue, ModuleRunnerImportMeta>>,\n]\n\nexport {}", "messages": null, "tools": null} {"id": "9f76e4b3cb12c398", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/create-vite/template-react-ts/src/App.tsx", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 3645, "sha256": "3a1357f76238220adcb3b1808e359f9182facf52db2e1ccb539bb1618de40bea", "text": "import { useState } from 'react'\nimport reactLogo from './assets/react.svg'\nimport viteLogo from './assets/vite.svg'\nimport heroImg from './assets/hero.png'\nimport './App.css'\n\nfunction App() {\n const [count, setCount] = useState(0)\n\n return (\n <>\n
\n
\n \"\"\n \"React\n \"Vite\n
\n
\n

Get started

\n

\n Edit src/App.tsx and save to test HMR\n

\n
\n setCount((count) => count + 1)}\n >\n Count is {count}\n \n
\n\n
\n\n
\n
\n \n \n \n

Documentation

\n

Your questions, answered

\n \n
\n
\n \n \n \n

Connect with us

\n

Join the Vite community

\n \n
\n
\n\n
\n
\n \n )\n}\n\nexport default App", "messages": null, "tools": null} {"id": "9f9989babbbae836", "category": "code", "domain": "code", "source": "flask", "license": "BSD-3-Clause", "license_url": "https://spdx.org/licenses/BSD-3-Clause.html", "path": "src/flask/json/__init__.py", "lang": "python", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/pallets/flask", "commit": "6a2f545bfd8ed31e19066a299296917e034aca58", "collector": "tools/harvest.py"}, "chars": 5582, "sha256": "402d455d87fc909809ae72c8191b9340728c8188fc024f01de98636bb3d4b1b9", "text": "from __future__ import annotations\n\nimport json as _json\nimport typing as t\n\nfrom ..globals import current_app\nfrom .provider import _default\n\nif t.TYPE_CHECKING: # pragma: no cover\n from ..wrappers import Response\n\n\ndef dumps(obj: t.Any, **kwargs: t.Any) -> str:\n \"\"\"Serialize data as JSON.\n\n If :data:`~flask.current_app` is available, it will use its\n :meth:`app.json.dumps() `\n method, otherwise it will use :func:`json.dumps`.\n\n :param obj: The data to serialize.\n :param kwargs: Arguments passed to the ``dumps`` implementation.\n\n .. versionchanged:: 2.3\n The ``app`` parameter was removed.\n\n .. versionchanged:: 2.2\n Calls ``current_app.json.dumps``, allowing an app to override\n the behavior.\n\n .. versionchanged:: 2.0.2\n :class:`decimal.Decimal` is supported by converting to a string.\n\n .. versionchanged:: 2.0\n ``encoding`` will be removed in Flask 2.1.\n\n .. versionchanged:: 1.0.3\n ``app`` can be passed directly, rather than requiring an app\n context for configuration.\n \"\"\"\n if current_app:\n return current_app.json.dumps(obj, **kwargs)\n\n kwargs.setdefault(\"default\", _default)\n return _json.dumps(obj, **kwargs)\n\n\ndef dump(obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None:\n \"\"\"Serialize data as JSON and write to a file.\n\n If :data:`~flask.current_app` is available, it will use its\n :meth:`app.json.dump() `\n method, otherwise it will use :func:`json.dump`.\n\n :param obj: The data to serialize.\n :param fp: A file opened for writing text. Should use the UTF-8\n encoding to be valid JSON.\n :param kwargs: Arguments passed to the ``dump`` implementation.\n\n .. versionchanged:: 2.3\n The ``app`` parameter was removed.\n\n .. versionchanged:: 2.2\n Calls ``current_app.json.dump``, allowing an app to override\n the behavior.\n\n .. versionchanged:: 2.0\n Writing to a binary file, and the ``encoding`` argument, will be\n removed in Flask 2.1.\n \"\"\"\n if current_app:\n current_app.json.dump(obj, fp, **kwargs)\n else:\n kwargs.setdefault(\"default\", _default)\n _json.dump(obj, fp, **kwargs)\n\n\ndef loads(s: str | bytes, **kwargs: t.Any) -> t.Any:\n \"\"\"Deserialize data as JSON.\n\n If :data:`~flask.current_app` is available, it will use its\n :meth:`app.json.loads() `\n method, otherwise it will use :func:`json.loads`.\n\n :param s: Text or UTF-8 bytes.\n :param kwargs: Arguments passed to the ``loads`` implementation.\n\n .. versionchanged:: 2.3\n The ``app`` parameter was removed.\n\n .. versionchanged:: 2.2\n Calls ``current_app.json.loads``, allowing an app to override\n the behavior.\n\n .. versionchanged:: 2.0\n ``encoding`` will be removed in Flask 2.1. The data must be a\n string or UTF-8 bytes.\n\n .. versionchanged:: 1.0.3\n ``app`` can be passed directly, rather than requiring an app\n context for configuration.\n \"\"\"\n if current_app:\n return current_app.json.loads(s, **kwargs)\n\n return _json.loads(s, **kwargs)\n\n\ndef load(fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any:\n \"\"\"Deserialize data as JSON read from a file.\n\n If :data:`~flask.current_app` is available, it will use its\n :meth:`app.json.load() `\n method, otherwise it will use :func:`json.load`.\n\n :param fp: A file opened for reading text or UTF-8 bytes.\n :param kwargs: Arguments passed to the ``load`` implementation.\n\n .. versionchanged:: 2.3\n The ``app`` parameter was removed.\n\n .. versionchanged:: 2.2\n Calls ``current_app.json.load``, allowing an app to override\n the behavior.\n\n .. versionchanged:: 2.2\n The ``app`` parameter will be removed in Flask 2.3.\n\n .. versionchanged:: 2.0\n ``encoding`` will be removed in Flask 2.1. The file must be text\n mode, or binary mode with UTF-8 bytes.\n \"\"\"\n if current_app:\n return current_app.json.load(fp, **kwargs)\n\n return _json.load(fp, **kwargs)\n\n\ndef jsonify(*args: t.Any, **kwargs: t.Any) -> Response:\n \"\"\"Serialize the given arguments as JSON, and return a\n :class:`~flask.Response` object with the ``application/json``\n mimetype. A dict or list returned from a view will be converted to a\n JSON response automatically without needing to call this.\n\n This requires an active app context, and calls\n :meth:`app.json.response() `.\n\n In debug mode, the output is formatted with indentation to make it\n easier to read. This may also be controlled by the provider.\n\n Either positional or keyword arguments can be given, not both.\n If no arguments are given, ``None`` is serialized.\n\n :param args: A single value to serialize, or multiple values to\n treat as a list to serialize.\n :param kwargs: Treat as a dict to serialize.\n\n .. versionchanged:: 2.2\n Calls ``current_app.json.response``, allowing an app to override\n the behavior.\n\n .. versionchanged:: 2.0.2\n :class:`decimal.Decimal` is supported by converting to a string.\n\n .. versionchanged:: 0.11\n Added support for serializing top-level arrays. This was a\n security risk in ancient browsers. See :ref:`security-json`.\n\n .. versionadded:: 0.2\n \"\"\"\n return current_app.json.response(*args, **kwargs) # type: ignore[return-value]", "messages": null, "tools": null} {"id": "9f9af45790b73ea3", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/operator__less.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 820, "sha256": "c890dff83577bad7d127b02682899bfe55193499d4c457fd13fd1804610bc99f", "text": "#include \n#include \n\nusing json = nlohmann::json;\n\nint main()\n{\n // create several JSON values\n json array_1 = {1, 2, 3};\n json array_2 = {1, 2, 4};\n json object_1 = {{\"A\", \"a\"}, {\"B\", \"b\"}};\n json object_2 = {{\"B\", \"b\"}, {\"A\", \"a\"}};\n json number_1 = 17;\n json number_2 = 17.0000000000001L;\n json string_1 = \"foo\";\n json string_2 = \"bar\";\n\n // output values and comparisons\n std::cout << std::boolalpha;\n std::cout << array_1 << \" == \" << array_2 << \" \" << (array_1 < array_2) << '\\n';\n std::cout << object_1 << \" == \" << object_2 << \" \" << (object_1 < object_2) << '\\n';\n std::cout << number_1 << \" == \" << number_2 << \" \" << (number_1 < number_2) << '\\n';\n std::cout << string_1 << \" == \" << string_2 << \" \" << (string_1 < string_2) << '\\n';\n}", "messages": null, "tools": null} {"id": "9fd8d5cc7486ae04", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/examples/nlohmann_define_type_non_intrusive_only_serialize_explicit.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 691, "sha256": "05687bc411785b8b0727274d3e0a9144cd954637501d9200a286ed09b3a03e1d", "text": "#include \n#include \n\nusing json = nlohmann::json;\nusing namespace nlohmann::literals;\n\nnamespace ns\n{\nstruct person\n{\n std::string name;\n std::string address;\n int age;\n};\n\ntemplate\nvoid to_json(BasicJsonType& nlohmann_json_j, const person& nlohmann_json_t)\n{\n nlohmann_json_j[\"name\"] = nlohmann_json_t.name;\n nlohmann_json_j[\"address\"] = nlohmann_json_t.address;\n nlohmann_json_j[\"age\"] = nlohmann_json_t.age;\n}\n} // namespace ns\n\nint main()\n{\n ns::person p = {\"Ned Flanders\", \"744 Evergreen Terrace\", 60};\n\n // serialization: person -> json\n json j = p;\n std::cout << \"serialization: \" << j << std::endl;\n}", "messages": null, "tools": null} {"id": "a0b577db3c8ebed1", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "scripts/mergeChangelog.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 5839, "sha256": "32677fa55494449d66f13d46774dd9515b5dab23ac9d13fdf88426e05fe5496a", "text": "/**\n * Merges prerelease (alpha/beta/rc) changelog entries into a single stable\n * release section within a package's CHANGELOG.md.\n *\n * Usage:\n * pnpm merge-changelog \n *\n * Example:\n * pnpm merge-changelog vite 8.0.0\n *\n * This will find the `## [8.0.0]` header in packages/vite/CHANGELOG.md,\n * collect all entries from its prerelease versions (e.g. 8.0.0-beta.1,\n * 8.0.0-rc.0), deduplicate and reorder them by category, append a\n * \"Beta Changelogs\" section with links to each prerelease's tagged\n * changelog, and write the merged result back to the file.\n */\nimport { readFile, writeFile } from 'node:fs/promises'\nimport path from 'node:path'\n\nconst pkg = process.argv[2]\nconst version = process.argv[3]\n\nif (!pkg || !version) {\n console.error('Usage: pnpm merge-changelog ')\n process.exit(1)\n}\n\nconst CATEGORY_ORDER = [\n '### ⚠ BREAKING CHANGES',\n '### Features',\n '### Bug Fixes',\n '### Performance Improvements',\n '### Documentation',\n '### Miscellaneous Chores',\n '### Code Refactoring',\n '### Tests',\n]\n\nfunction escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nconst versionHeaderRe = /^## (?:)?\\[/\n\nfunction findReleaseHeaderIndex(lines: string[], version: string): number {\n const re = new RegExp(`^## (?:)?\\\\[${escapeRegex(version)}\\\\]`)\n const idx = lines.findIndex((l) => re.test(l))\n if (idx === -1) {\n console.error(`Could not find header for version ${version}`)\n process.exit(1)\n }\n return idx\n}\n\nfunction findEndBoundary(\n lines: string[],\n startIdx: number,\n version: string,\n): number {\n const prereleaseRe = new RegExp(\n `^## (?:)?\\\\[${escapeRegex(version)}-(beta|alpha|rc)\\\\.\\\\d+\\\\]`,\n )\n for (let i = startIdx + 1; i < lines.length; i++) {\n if (versionHeaderRe.test(lines[i]) && !prereleaseRe.test(lines[i])) {\n return i\n }\n }\n return lines.length\n}\n\nfunction parseCategories(releaseLines: string[]): Map {\n const categories = new Map()\n let currentCategory: string | null = null\n\n for (let i = 1; i < releaseLines.length; i++) {\n const line = releaseLines[i]\n if (versionHeaderRe.test(line)) {\n currentCategory = null\n continue\n }\n if (line.startsWith('### ')) {\n currentCategory = line.trim()\n if (!categories.has(currentCategory)) {\n categories.set(currentCategory, [])\n }\n continue\n }\n\n if (currentCategory && line.trim() !== '') {\n categories.get(currentCategory)!.push(line)\n }\n }\n\n return categories\n}\n\nfunction findPreviousStableVersion(lines: string[], startIdx: number): string {\n for (let i = startIdx; i < lines.length; i++) {\n const match = lines[i].match(/^## (?:)?\\[([^\\]]+)\\]/)\n if (match) {\n const v = match[1]\n if (!/alpha|beta|rc/.test(v)) {\n return v\n }\n }\n }\n return ''\n}\n\nfunction updateHeaderCompareLink(\n headerLine: string,\n prevStable: string,\n pkg: string,\n version: string,\n): string {\n if (!prevStable) return headerLine\n const tagPrefix = pkg === 'vite' ? 'v' : `${pkg}@`\n return headerLine.replace(\n /compare\\/[^)]+/,\n `compare/${tagPrefix}${prevStable}...${tagPrefix}${version}`,\n )\n}\n\nfunction collectPrereleaseHeaders(\n releaseLines: string[],\n pkg: string,\n): string[] {\n const lines: string[] = []\n for (const line of releaseLines) {\n const match = line.match(\n /^## (?:)?\\[([^\\]]+)\\]\\(([^)]+)\\)(?: \\((\\d{4}-\\d{2}-\\d{2})\\))?/,\n )\n if (!match) continue\n const [, ver, compareUrl, date] = match\n if (!/alpha|beta|rc/.test(ver)) continue\n\n const tagPrefix = pkg === 'vite' ? 'v' : `${pkg}@`\n const tag = `${tagPrefix}${ver}`\n const header = date\n ? `#### [${ver}](${compareUrl}) (${date})`\n : `#### [${ver}](${compareUrl})`\n lines.push(\n header,\n '',\n `See [${ver} changelog](https://github.com/vitejs/vite/blob/${tag}/packages/${pkg}/CHANGELOG.md)`,\n '',\n )\n }\n return lines\n}\n\nfunction buildOutputLines(\n headerLine: string,\n categories: Map,\n prereleaseLines: string[],\n): string[] {\n const hasUnknownCategories = [...categories.keys()].filter(\n (c) => !CATEGORY_ORDER.includes(c),\n )\n if (hasUnknownCategories.length > 0) {\n throw new Error(\n `Unknown categories found: ${hasUnknownCategories.join(', ')}`,\n )\n }\n\n const outputLines: string[] = [headerLine, '']\n for (const category of CATEGORY_ORDER) {\n const items = categories.get(category)\n if (items && items.length > 0) {\n outputLines.push(category, '')\n outputLines.push(...items)\n outputLines.push('')\n }\n }\n\n if (prereleaseLines.length > 0) {\n outputLines.push('### Beta Changelogs', '', ...prereleaseLines)\n }\n\n return outputLines\n}\n\nconst filePath = path.resolve(\n // eslint-disable-next-line n/no-unsupported-features/node-builtins\n import.meta.dirname,\n `../packages/${pkg}/CHANGELOG.md`,\n)\nconst content = await readFile(filePath, 'utf-8')\nconst lines = content.split('\\n')\n\nconst releaseHeaderIdx = findReleaseHeaderIndex(lines, version)\nconst endIdx = findEndBoundary(lines, releaseHeaderIdx, version)\nconst releaseLines = lines.slice(releaseHeaderIdx, endIdx)\n\nconst categories = parseCategories(releaseLines)\nconst prereleaseLines = collectPrereleaseHeaders(releaseLines, pkg)\nconst prevStable = findPreviousStableVersion(lines, endIdx)\nconst headerLine = updateHeaderCompareLink(\n releaseLines[0],\n prevStable,\n pkg,\n version,\n)\nconst outputLines = buildOutputLines(headerLine, categories, prereleaseLines)\n\nconst result = [\n ...lines.slice(0, releaseHeaderIdx),\n ...outputLines,\n ...lines.slice(endIdx),\n].join('\\n')\n\nawait writeFile(filePath, result, 'utf-8')\nconsole.log(`Merged prerelease changelog sections for ${version} in ${pkg}`)", "messages": null, "tools": null} {"id": "a0f29a1356485ed8", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/guide/assets.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 6546, "sha256": "a76fe81d2a98f9bebea19799d26edad121be3ca6ea74a37c84ace1cd32489210", "text": "# Static Asset Handling\n\n- Related: [Public Base Path](./build#public-base-path)\n- Related: [`assetsInclude` config option](/config/shared-options.md#assetsinclude)\n\n## Importing Asset as URL\n\nImporting a static asset will return the resolved public URL when it is served:\n\n```js twoslash\nimport 'vite/client'\n// ---cut---\nimport imgUrl from './img.png'\ndocument.getElementById('hero-img').src = imgUrl\n```\n\nFor example, `imgUrl` will be `/src/img.png` during development, and become `/assets/img.2d8efhg.png` in the production build.\n\nThe behavior is similar to webpack's `file-loader`. The difference is that the import can be either using absolute public paths (based on project root during dev) or relative paths.\n\n- `url()` references in CSS are handled the same way.\n\n- If using the Vue plugin, asset references in Vue SFC templates are automatically converted into imports.\n\n- Common image, media, and font filetypes are detected as assets automatically. You can extend the internal list using the [`assetsInclude` option](/config/shared-options.md#assetsinclude).\n\n- Referenced assets are included as part of the build assets graph, will get hashed file names, and can be processed by plugins for optimization.\n\n- Assets smaller in bytes than the [`assetsInlineLimit` option](/config/build-options.md#build-assetsinlinelimit) will be inlined as base64 data URLs.\n\n- Git LFS placeholders are automatically excluded from inlining because they do not contain the content of the file they represent. To get inlining, make sure to download the file contents via Git LFS before building.\n\n- TypeScript, by default, does not recognize static asset imports as valid modules. To fix this, include [`vite/client`](./features#client-types).\n\n::: tip Inlining SVGs through `url()`\nWhen passing a URL of SVG to a manually constructed `url()` by JS, the variable should be wrapped within double quotes.\n\n```js twoslash\nimport 'vite/client'\n// ---cut---\nimport imgUrl from './img.svg'\ndocument.getElementById('hero-img').style.background = `url(\"${imgUrl}\")`\n```\n\n:::\n\n### Explicit URL Imports\n\nAssets that are not included in the internal list or in `assetsInclude` can be explicitly imported as a URL using the `?url` suffix. This is useful, for example, to import [Houdini Paint Worklets](https://developer.mozilla.org/en-US/docs/Web/API/CSS/paintWorklet_static).\n\n```js twoslash\nimport 'vite/client'\n// ---cut---\nimport workletURL from 'extra-scalloped-border/worklet.js?url'\nCSS.paintWorklet.addModule(workletURL)\n```\n\n### Explicit Inline Handling\n\nAssets can be explicitly imported with inlining or no inlining using the `?inline` or `?no-inline` suffix respectively.\n\n```js twoslash\nimport 'vite/client'\n// ---cut---\nimport imgUrl1 from './img.svg?no-inline'\nimport imgUrl2 from './img.png?inline'\n```\n\n### Importing Asset as String\n\nAssets can be imported as strings using the `?raw` suffix.\n\n```js twoslash\nimport 'vite/client'\n// ---cut---\nimport shaderString from './shader.glsl?raw'\n```\n\n### Importing Script as a Worker\n\nScripts can be imported as web workers with the `?worker` or `?sharedworker` suffix.\n\n```js twoslash\nimport 'vite/client'\n// ---cut---\n// Separate chunk in the production build\nimport Worker from './shader.js?worker'\nconst worker = new Worker()\n```\n\n```js twoslash\nimport 'vite/client'\n// ---cut---\n// sharedworker\nimport SharedWorker from './shader.js?sharedworker'\nconst sharedWorker = new SharedWorker()\n```\n\n```js twoslash\nimport 'vite/client'\n// ---cut---\n// Inlined as base64 strings\nimport InlineWorker from './shader.js?worker&inline'\n```\n\nCheck out the [Web Worker section](./features.md#web-workers) for more details.\n\n## The `public` Directory\n\nIf you have assets that are:\n\n- Never referenced in source code (e.g. `robots.txt`)\n- Must retain the exact same file name (without hashing)\n- ...or you simply don't want to have to import an asset first just to get its URL\n\nThen you can place the asset in a special `public` directory under your project root. Assets in this directory will be served at root path `/` during dev, and copied to the root of the dist directory as-is.\n\nThe directory defaults to `/public`, but can be configured via the [`publicDir` option](/config/shared-options.md#publicdir).\n\nNote that you should always reference `public` assets using root absolute path - for example, `public/icon.png` should be referenced in source code as `/icon.png`.\n\n::: tip Choosing between imports and the `public` directory\n\nIn general, prefer **importing assets** unless you specifically need the guarantees provided by the `public` directory.\n\n:::\n\n## new URL(url, import.meta.url)\n\n[import.meta.url](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import.meta) is a native ESM feature that exposes the current module's URL. Combining it with the native [URL constructor](https://developer.mozilla.org/en-US/docs/Web/API/URL), we can obtain the full, resolved URL of a static asset using relative path from a JavaScript module:\n\n```js\nconst imgUrl = new URL('./img.png', import.meta.url).href\n\ndocument.getElementById('hero-img').src = imgUrl\n```\n\nThis works natively in modern browsers - in fact, Vite doesn't need to process this code at all during development!\n\nThis pattern also supports dynamic URLs via template literals:\n\n```js\nfunction getImageUrl(name) {\n // note that this does not include files in subdirectories\n return new URL(`./dir/${name}.png`, import.meta.url).href\n}\n```\n\nDuring the production build, Vite will perform necessary transforms so that the URLs still point to the correct location even after bundling and asset hashing. However, the URL string must be static so it can be analyzed, otherwise the code will be left as is, which can cause runtime errors if `build.target` does not support `import.meta.url`.\n\n```js\n// Vite will not transform this\nconst imgUrl = new URL(imagePath, import.meta.url).href\n```\n\n::: details How it works\n\nVite will transform the `getImageUrl` function to:\n\n```js\nimport __img0png from './dir/img0.png'\nimport __img1png from './dir/img1.png'\n\nfunction getImageUrl(name) {\n const modules = {\n './dir/img0.png': __img0png,\n './dir/img1.png': __img1png,\n }\n return new URL(modules[`./dir/${name}.png`], import.meta.url).href\n}\n```\n\n:::\n\n::: warning Does not work with SSR\nThis pattern does not work if you are using Vite for Server-Side Rendering, because `import.meta.url` has different semantics in browsers vs. Node.js. The server bundle also cannot determine the client host URL ahead of time.\n:::", "messages": null, "tools": null} {"id": "a1a8f8450eadd6a4", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/node/__tests__/plugins/index.spec.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 4518, "sha256": "4878457748fb8188a8d8a3ecb4a09acffbfc0ca854c29fd5cff70b86158ecfb0", "text": "import { RUNTIME_MODULE_ID } from 'rolldown'\nimport { exactRegex } from 'rolldown/filter'\nimport { afterAll, describe, expect, test, vi } from 'vitest'\nimport { type InlineConfig, type Plugin, build, createServer } from '../..'\n\nconst getConfigWithPlugin = (\n plugins: Plugin[],\n input?: string[],\n): InlineConfig => {\n return {\n configFile: false,\n server: { middlewareMode: true, ws: false },\n optimizeDeps: { noDiscovery: true, include: [] },\n build: { rolldownOptions: { input }, write: false },\n plugins,\n logLevel: 'silent',\n }\n}\n\ndescribe('hook filter with plugin container', async () => {\n const resolveId = vi.fn()\n const load = vi.fn()\n const transformWithId = vi.fn()\n const transformWithCode = vi.fn()\n const any = expect.toSatisfy(() => true) // anything including undefined and null\n const config = getConfigWithPlugin([\n {\n name: 'test',\n resolveId: {\n filter: { id: /\\.js$/ },\n handler: resolveId,\n },\n load: {\n filter: { id: '**/*.js' },\n handler: load,\n },\n transform: {\n filter: { id: '**/*.js' },\n handler: transformWithId,\n },\n },\n {\n name: 'test2',\n transform: {\n filter: { code: 'import.meta' },\n handler: transformWithCode,\n },\n },\n ])\n const server = await createServer(config)\n afterAll(async () => {\n await server.close()\n })\n const pluginContainer = server.environments.ssr.pluginContainer\n\n test('resolveId', async () => {\n await pluginContainer.resolveId('foo.js')\n await pluginContainer.resolveId('foo.ts')\n expect(resolveId).toHaveBeenCalledTimes(1)\n expect(resolveId).toHaveBeenCalledWith('foo.js', any, any)\n })\n\n test('load', async () => {\n await pluginContainer.load('foo.js')\n await pluginContainer.load('foo.ts')\n expect(load).toHaveBeenCalledTimes(1)\n expect(load).toHaveBeenCalledWith('foo.js', any)\n })\n\n test('transform', async () => {\n await server.environments.ssr.moduleGraph.ensureEntryFromUrl('foo.js')\n await server.environments.ssr.moduleGraph.ensureEntryFromUrl('foo.ts')\n\n await pluginContainer.transform('import_meta', 'foo.js')\n await pluginContainer.transform('import.meta', 'foo.ts')\n expect(transformWithId).toHaveBeenCalledTimes(1)\n expect(transformWithId).toHaveBeenCalledWith(\n expect.stringContaining('import_meta'),\n 'foo.js',\n any,\n )\n expect(transformWithCode).toHaveBeenCalledTimes(1)\n expect(transformWithCode).toHaveBeenCalledWith(\n expect.stringContaining('import.meta'),\n 'foo.ts',\n any,\n )\n })\n})\n\ndescribe('hook filter with build', async () => {\n const resolveId = vi.fn()\n const load = vi.fn()\n const transformWithId = vi.fn()\n const transformWithCode = vi.fn()\n const any = expect.anything()\n const config = getConfigWithPlugin(\n [\n {\n name: 'test',\n resolveId: {\n filter: { id: /\\.js$/ },\n handler: resolveId,\n },\n load: {\n filter: { id: '**/*.js' },\n handler: load,\n },\n transform: {\n filter: {\n id: {\n include: '**/*.js',\n exclude: exactRegex(RUNTIME_MODULE_ID),\n },\n },\n handler: transformWithId,\n },\n },\n {\n name: 'test2',\n transform: {\n filter: { code: 'import.meta' },\n handler: transformWithCode,\n },\n },\n {\n name: 'resolver',\n resolveId(id) {\n return id\n },\n load(id) {\n if (id === 'foo.js') {\n return 'import \"foo.ts\"\\n' + 'import_meta'\n }\n if (id === 'foo.ts') {\n return 'import.meta'\n }\n },\n },\n ],\n ['foo.js', 'foo.ts'],\n )\n await build(config)\n\n test('resolveId', async () => {\n expect(resolveId).toHaveBeenCalledTimes(1)\n expect(resolveId).toHaveBeenCalledWith('foo.js', undefined, any)\n })\n\n test('load', async () => {\n expect(load).toHaveBeenCalledTimes(1)\n expect(load).toHaveBeenCalledWith('foo.js', any)\n })\n\n test('transform', async () => {\n expect(transformWithId).toHaveBeenCalledTimes(1)\n expect(transformWithId).toHaveBeenCalledWith(\n expect.stringContaining('import_meta'),\n 'foo.js',\n any,\n )\n expect(transformWithCode).toHaveBeenCalledTimes(1)\n expect(transformWithCode).toHaveBeenCalledWith(\n expect.stringContaining('import.meta'),\n 'foo.ts',\n any,\n )\n })\n})", "messages": null, "tools": null} {"id": "a203781c00b1d930", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "tests/thirdparty/Fuzzer/test/ThreadedLeakTest.cpp", "lang": "cpp", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 455, "sha256": "564c5217abf96b1b88aca2e1b6c744dad91cf679a400d43541a018341823d9d8", "text": "// This file is distributed under the University of Illinois Open Source\n// License. See LICENSE.TXT for details.\n\n// The fuzzer should find a leak in a non-main thread.\n#include \n#include \n#include \n\nstatic volatile int *Sink;\n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {\n if (Size == 0) return 0;\n if (Data[0] != 'F') return 0;\n std::thread T([&] { Sink = new int; });\n T.join();\n return 0;\n}", "messages": null, "tools": null} {"id": "a3600fffdf2d1a05", "category": "code", "domain": "code", "source": "ripgrep", "license": "MIT OR Unlicense", "license_url": "https://spdx.org/licenses/MIT.html", "path": "crates/regex/src/matcher.rs", "lang": "rust", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/BurntSushi/ripgrep", "commit": "3fce3b5bb0236da2df6d99672afb8a719642eca7", "collector": "tools/harvest.py"}, "chars": 25596, "sha256": "0404b9cbd9819da680b96d66d5d370e1522aba8a0756b38717b52b6a2aa14a4c", "text": "use {\n grep_matcher::{\n ByteSet, Captures, LineMatchKind, LineTerminator, Match, Matcher,\n NoError,\n },\n regex_automata::{\n Input, PatternID, meta::Regex,\n util::captures::Captures as AutomataCaptures,\n },\n};\n\nuse crate::{config::Config, error::Error, literal::InnerLiterals};\n\n/// A builder for constructing a `Matcher` using regular expressions.\n///\n/// This builder re-exports many of the same options found on the regex crate's\n/// builder, in addition to a few other options such as smart case, word\n/// matching and the ability to set a line terminator which may enable certain\n/// types of optimizations.\n///\n/// The syntax supported is documented as part of the regex crate:\n/// .\n#[derive(Clone, Debug)]\npub struct RegexMatcherBuilder {\n config: Config,\n}\n\nimpl Default for RegexMatcherBuilder {\n fn default() -> RegexMatcherBuilder {\n RegexMatcherBuilder::new()\n }\n}\n\nimpl RegexMatcherBuilder {\n /// Create a new builder for configuring a regex matcher.\n pub fn new() -> RegexMatcherBuilder {\n RegexMatcherBuilder { config: Config::default() }\n }\n\n /// Build a new matcher using the current configuration for the provided\n /// pattern.\n ///\n /// The syntax supported is documented as part of the regex crate:\n /// .\n pub fn build(&self, pattern: &str) -> Result {\n self.build_many(&[pattern])\n }\n\n /// Build a new matcher using the current configuration for the provided\n /// patterns. The resulting matcher behaves as if all of the patterns\n /// given are joined together into a single alternation. That is, it\n /// reports matches where at least one of the given patterns matches.\n pub fn build_many>(\n &self,\n patterns: &[P],\n ) -> Result {\n let mut chir = self.config.build_many(patterns)?;\n // 'whole_line' is a strict subset of 'word', so when it is enabled,\n // we don't need to both with any specific to word matching.\n if chir.config().whole_line {\n chir = chir.into_whole_line();\n } else if chir.config().word {\n chir = chir.into_word();\n }\n let regex = chir.to_regex()?;\n log::trace!(\"final regex: {:?}\", chir.hir().to_string());\n\n let non_matching_bytes = chir.non_matching_bytes();\n // If we can pick out some literals from the regex, then we might be\n // able to build a faster regex that quickly identifies candidate\n // matching lines. The regex engine will do what it can on its own, but\n // we can specifically do a little more when a line terminator is set.\n // For example, for a regex like `\\w+foo\\w+`, we can look for `foo`,\n // and when a match is found, look for the line containing `foo` and\n // then run the original regex on only that line. (In this case, the\n // regex engine is likely to handle this case for us since it's so\n // simple, but the idea applies.)\n let fast_line_regex = InnerLiterals::new(&chir, ®ex).one_regex()?;\n\n // We override the line terminator in case the configured HIR doesn't\n // support it.\n let mut config = self.config.clone();\n config.line_terminator = chir.line_terminator();\n Ok(RegexMatcher { config, regex, fast_line_regex, non_matching_bytes })\n }\n\n /// Build a new matcher from a plain alternation of literals.\n ///\n /// Depending on the configuration set by the builder, this may be able to\n /// build a matcher substantially faster than by joining the patterns with\n /// a `|` and calling `build`.\n pub fn build_literals>(\n &self,\n literals: &[B],\n ) -> Result {\n self.build_many(literals)\n }\n\n /// Set the value for the case insensitive (`i`) flag.\n ///\n /// When enabled, letters in the pattern will match both upper case and\n /// lower case variants.\n pub fn case_insensitive(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.config.case_insensitive = yes;\n self\n }\n\n /// Whether to enable \"smart case\" or not.\n ///\n /// When smart case is enabled, the builder will automatically enable\n /// case insensitive matching based on how the pattern is written. Namely,\n /// case insensitive mode is enabled when both of the following things\n /// are true:\n ///\n /// 1. The pattern contains at least one literal character. For example,\n /// `a\\w` contains a literal (`a`) but `\\w` does not.\n /// 2. Of the literals in the pattern, none of them are considered to be\n /// uppercase according to Unicode. For example, `foo\\pL` has no\n /// uppercase literals but `Foo\\pL` does.\n pub fn case_smart(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.config.case_smart = yes;\n self\n }\n\n /// Set the value for the multi-line matching (`m`) flag.\n ///\n /// When enabled, `^` matches the beginning of lines and `$` matches the\n /// end of lines.\n ///\n /// By default, they match beginning/end of the input.\n pub fn multi_line(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.config.multi_line = yes;\n self\n }\n\n /// Set the value for the any character (`s`) flag, where in `.` matches\n /// anything when `s` is set and matches anything except for new line when\n /// it is not set (the default).\n ///\n /// N.B. \"matches anything\" means \"any byte\" when Unicode is disabled and\n /// means \"any valid UTF-8 encoding of any Unicode scalar value\" when\n /// Unicode is enabled.\n pub fn dot_matches_new_line(\n &mut self,\n yes: bool,\n ) -> &mut RegexMatcherBuilder {\n self.config.dot_matches_new_line = yes;\n self\n }\n\n /// Set the value for the greedy swap (`U`) flag.\n ///\n /// When enabled, a pattern like `a*` is lazy (tries to find shortest\n /// match) and `a*?` is greedy (tries to find longest match).\n ///\n /// By default, `a*` is greedy and `a*?` is lazy.\n pub fn swap_greed(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.config.swap_greed = yes;\n self\n }\n\n /// Set the value for the ignore whitespace (`x`) flag.\n ///\n /// When enabled, whitespace such as new lines and spaces will be ignored\n /// between expressions of the pattern, and `#` can be used to start a\n /// comment until the next new line.\n pub fn ignore_whitespace(\n &mut self,\n yes: bool,\n ) -> &mut RegexMatcherBuilder {\n self.config.ignore_whitespace = yes;\n self\n }\n\n /// Set the value for the Unicode (`u`) flag.\n ///\n /// Enabled by default. When disabled, character classes such as `\\w` only\n /// match ASCII word characters instead of all Unicode word characters.\n pub fn unicode(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.config.unicode = yes;\n self\n }\n\n /// Whether to support octal syntax or not.\n ///\n /// Octal syntax is a little-known way of uttering Unicode codepoints in\n /// a regular expression. For example, `a`, `\\x61`, `\\u0061` and\n /// `\\141` are all equivalent regular expressions, where the last example\n /// shows octal syntax.\n ///\n /// While supporting octal syntax isn't in and of itself a problem, it does\n /// make good error messages harder. That is, in PCRE based regex engines,\n /// syntax like `\\0` invokes a backreference, which is explicitly\n /// unsupported in Rust's regex engine. However, many users expect it to\n /// be supported. Therefore, when octal support is disabled, the error\n /// message will explicitly mention that backreferences aren't supported.\n ///\n /// Octal syntax is disabled by default.\n pub fn octal(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.config.octal = yes;\n self\n }\n\n /// Set the approximate size limit of the compiled regular expression.\n ///\n /// This roughly corresponds to the number of bytes occupied by a single\n /// compiled program. If the program exceeds this number, then a\n /// compilation error is returned.\n pub fn size_limit(&mut self, bytes: usize) -> &mut RegexMatcherBuilder {\n self.config.size_limit = bytes;\n self\n }\n\n /// Set the approximate size of the cache used by the DFA.\n ///\n /// This roughly corresponds to the number of bytes that the DFA will\n /// use while searching.\n ///\n /// Note that this is a *per thread* limit. There is no way to set a global\n /// limit. In particular, if a regex is used from multiple threads\n /// simultaneously, then each thread may use up to the number of bytes\n /// specified here.\n pub fn dfa_size_limit(\n &mut self,\n bytes: usize,\n ) -> &mut RegexMatcherBuilder {\n self.config.dfa_size_limit = bytes;\n self\n }\n\n /// Set the nesting limit for this parser.\n ///\n /// The nesting limit controls how deep the abstract syntax tree is allowed\n /// to be. If the AST exceeds the given limit (e.g., with too many nested\n /// groups), then an error is returned by the parser.\n ///\n /// The purpose of this limit is to act as a heuristic to prevent stack\n /// overflow for consumers that do structural induction on an `Ast` using\n /// explicit recursion. While this crate never does this (instead using\n /// constant stack space and moving the call stack to the heap), other\n /// crates may.\n ///\n /// This limit is not checked until the entire Ast is parsed. Therefore,\n /// if callers want to put a limit on the amount of heap space used, then\n /// they should impose a limit on the length, in bytes, of the concrete\n /// pattern string. In particular, this is viable since this parser\n /// implementation will limit itself to heap space proportional to the\n /// length of the pattern string.\n ///\n /// Note that a nest limit of `0` will return a nest limit error for most\n /// patterns but not all. For example, a nest limit of `0` permits `a` but\n /// not `ab`, since `ab` requires a concatenation, which results in a nest\n /// depth of `1`. In general, a nest limit is not something that manifests\n /// in an obvious way in the concrete syntax, therefore, it should not be\n /// used in a granular way.\n pub fn nest_limit(&mut self, limit: u32) -> &mut RegexMatcherBuilder {\n self.config.nest_limit = limit;\n self\n }\n\n /// Set an ASCII line terminator for the matcher.\n ///\n /// The purpose of setting a line terminator is to enable a certain class\n /// of optimizations that can make line oriented searching faster. Namely,\n /// when a line terminator is enabled, then the builder will guarantee that\n /// the resulting matcher will never be capable of producing a match that\n /// contains the line terminator. Because of this guarantee, users of the\n /// resulting matcher do not need to slowly execute a search line by line\n /// for line oriented search.\n ///\n /// If the aforementioned guarantee about not matching a line terminator\n /// cannot be made because of how the pattern was written, then the builder\n /// will return an error when attempting to construct the matcher. For\n /// example, the pattern `a\\sb` will be transformed such that it can never\n /// match `a\\nb` (when `\\n` is the line terminator), but the pattern `a\\nb`\n /// will result in an error since the `\\n` cannot be easily removed without\n /// changing the fundamental intent of the pattern.\n ///\n /// If the given line terminator isn't an ASCII byte (`<=127`), then the\n /// builder will return an error when constructing the matcher.\n pub fn line_terminator(\n &mut self,\n line_term: Option,\n ) -> &mut RegexMatcherBuilder {\n self.config.line_terminator = line_term.map(LineTerminator::byte);\n self\n }\n\n /// Ban a byte from occurring in a regular expression pattern.\n ///\n /// If this byte is found in the regex pattern, then an error will be\n /// returned at construction time.\n ///\n /// This is useful when binary detection is enabled. Callers will likely\n /// want to ban the same byte that is used to detect binary data, i.e.,\n /// the NUL byte. The reason for this is that when binary detection is\n /// enabled, it's impossible to match a NUL byte because binary detection\n /// will either quit when one is found, or will convert NUL bytes to line\n /// terminators to avoid exorbitant heap usage.\n pub fn ban_byte(&mut self, byte: Option) -> &mut RegexMatcherBuilder {\n self.config.ban = byte;\n self\n }\n\n /// Set the line terminator to `\\r\\n` and enable CRLF matching for `$` in\n /// regex patterns.\n ///\n /// This method sets two distinct settings:\n ///\n /// 1. It causes the line terminator for the matcher to be `\\r\\n`. Namely,\n /// this prevents the matcher from ever producing a match that contains\n /// a `\\r` or `\\n`.\n /// 2. It enables CRLF mode for `^` and `$`. This means that line anchors\n /// will treat both `\\r` and `\\n` as line terminators, but will never\n /// match between a `\\r` and `\\n`.\n ///\n /// Note that if you do not wish to set the line terminator but would\n /// still like `$` to match `\\r\\n` line terminators, then it is valid to\n /// call `crlf(true)` followed by `line_terminator(None)`. Ordering is\n /// important, since `crlf` sets the line terminator, but `line_terminator`\n /// does not touch the `crlf` setting.\n pub fn crlf(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n if yes {\n self.config.line_terminator = Some(LineTerminator::crlf());\n } else {\n self.config.line_terminator = None;\n }\n self.config.crlf = yes;\n self\n }\n\n /// Require that all matches occur on word boundaries.\n ///\n /// Enabling this option is subtly different than putting `\\b` assertions\n /// on both sides of your pattern. In particular, a `\\b` assertion requires\n /// that one side of it match a word character while the other match a\n /// non-word character. This option, in contrast, merely requires that\n /// one side match a non-word character.\n ///\n /// For example, `\\b-2\\b` will not match `foo -2 bar` since `-` is not a\n /// word character. However, `-2` with this `word` option enabled will\n /// match the `-2` in `foo -2 bar`.\n pub fn word(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.config.word = yes;\n self\n }\n\n /// Whether the patterns should be treated as literal strings or not. When\n /// this is active, all characters, including ones that would normally be\n /// special regex meta characters, are matched literally.\n pub fn fixed_strings(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.config.fixed_strings = yes;\n self\n }\n\n /// Whether each pattern should match the entire line or not. This is\n /// equivalent to surrounding the pattern with `(?m:^)` and `(?m:$)`.\n pub fn whole_line(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.config.whole_line = yes;\n self\n }\n}\n\n/// An implementation of the `Matcher` trait using Rust's standard regex\n/// library.\n#[derive(Clone, Debug)]\npub struct RegexMatcher {\n /// The configuration specified by the caller.\n config: Config,\n /// The regular expression compiled from the pattern provided by the\n /// caller.\n regex: Regex,\n /// A regex that never reports false negatives but may report false\n /// positives that is believed to be capable of being matched more quickly\n /// than `regex`. Typically, this is a single literal or an alternation\n /// of literals.\n fast_line_regex: Option,\n /// A set of bytes that will never appear in a match.\n non_matching_bytes: ByteSet,\n}\n\nimpl RegexMatcher {\n /// Create a new matcher from the given pattern using the default\n /// configuration.\n pub fn new(pattern: &str) -> Result {\n RegexMatcherBuilder::new().build(pattern)\n }\n\n /// Create a new matcher from the given pattern using the default\n /// configuration, but matches lines terminated by `\\n`.\n ///\n /// This is meant to be a convenience constructor for\n /// using a `RegexMatcherBuilder` and setting its\n /// [`line_terminator`](RegexMatcherBuilder::method.line_terminator) to\n /// `\\n`. The purpose of using this constructor is to permit special\n /// optimizations that help speed up line oriented search. These types of\n /// optimizations are only appropriate when matches span no more than one\n /// line. For this reason, this constructor will return an error if the\n /// given pattern contains a literal `\\n`. Other uses of `\\n` (such as in\n /// `\\s`) are removed transparently.\n pub fn new_line_matcher(pattern: &str) -> Result {\n RegexMatcherBuilder::new().line_terminator(Some(b'\\n')).build(pattern)\n }\n}\n\n// This implementation just dispatches on the internal matcher impl except\n// for the line terminator optimization, which is possibly executed via\n// `fast_line_regex`.\nimpl Matcher for RegexMatcher {\n type Captures = RegexCaptures;\n type Error = NoError;\n\n #[inline]\n fn find_at(\n &self,\n haystack: &[u8],\n at: usize,\n ) -> Result, NoError> {\n let input = Input::new(haystack).span(at..haystack.len());\n Ok(self.regex.find(input).map(|m| Match::new(m.start(), m.end())))\n }\n\n #[inline]\n fn new_captures(&self) -> Result {\n Ok(RegexCaptures::new(self.regex.create_captures()))\n }\n\n #[inline]\n fn capture_count(&self) -> usize {\n self.regex.captures_len()\n }\n\n #[inline]\n fn capture_index(&self, name: &str) -> Option {\n self.regex.group_info().to_index(PatternID::ZERO, name)\n }\n\n #[inline]\n fn try_find_iter(\n &self,\n haystack: &[u8],\n mut matched: F,\n ) -> Result, NoError>\n where\n F: FnMut(Match) -> Result,\n {\n for m in self.regex.find_iter(haystack) {\n match matched(Match::new(m.start(), m.end())) {\n Ok(true) => continue,\n Ok(false) => return Ok(Ok(())),\n Err(err) => return Ok(Err(err)),\n }\n }\n Ok(Ok(()))\n }\n\n #[inline]\n fn captures_at(\n &self,\n haystack: &[u8],\n at: usize,\n caps: &mut RegexCaptures,\n ) -> Result {\n let input = Input::new(haystack).span(at..haystack.len());\n let caps = caps.captures_mut();\n self.regex.search_captures(&input, caps);\n Ok(caps.is_match())\n }\n\n #[inline]\n fn shortest_match_at(\n &self,\n haystack: &[u8],\n at: usize,\n ) -> Result, NoError> {\n let input = Input::new(haystack).span(at..haystack.len());\n Ok(self.regex.search_half(&input).map(|hm| hm.offset()))\n }\n\n #[inline]\n fn non_matching_bytes(&self) -> Option<&ByteSet> {\n Some(&self.non_matching_bytes)\n }\n\n #[inline]\n fn line_terminator(&self) -> Option {\n self.config.line_terminator\n }\n\n #[inline]\n fn find_candidate_line(\n &self,\n haystack: &[u8],\n ) -> Result, NoError> {\n Ok(match self.fast_line_regex {\n Some(ref regex) => {\n let input = Input::new(haystack);\n regex\n .search_half(&input)\n .map(|hm| LineMatchKind::Candidate(hm.offset()))\n }\n None => {\n self.shortest_match(haystack)?.map(LineMatchKind::Confirmed)\n }\n })\n }\n}\n\n/// Represents the match offsets of each capturing group in a match.\n///\n/// The first, or `0`th capture group, always corresponds to the entire match\n/// and is guaranteed to be present when a match occurs. The next capture\n/// group, at index `1`, corresponds to the first capturing group in the regex,\n/// ordered by the position at which the left opening parenthesis occurs.\n///\n/// Note that not all capturing groups are guaranteed to be present in a match.\n/// For example, in the regex, `(?P\\w)|(?P\\W)`, only one of `foo`\n/// or `bar` will ever be set in any given match.\n///\n/// In order to access a capture group by name, you'll need to first find the\n/// index of the group using the corresponding matcher's `capture_index`\n/// method, and then use that index with `RegexCaptures::get`.\n#[derive(Clone, Debug)]\npub struct RegexCaptures {\n /// Where the captures are stored.\n caps: AutomataCaptures,\n}\n\nimpl Captures for RegexCaptures {\n #[inline]\n fn len(&self) -> usize {\n self.caps.group_info().all_group_len()\n }\n\n #[inline]\n fn get(&self, i: usize) -> Option {\n self.caps.get_group(i).map(|sp| Match::new(sp.start, sp.end))\n }\n}\n\nimpl RegexCaptures {\n #[inline]\n pub(crate) fn new(caps: AutomataCaptures) -> RegexCaptures {\n RegexCaptures { caps }\n }\n\n #[inline]\n pub(crate) fn captures_mut(&mut self) -> &mut AutomataCaptures {\n &mut self.caps\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n // Test that enabling word matches does the right thing and demonstrate\n // the difference between it and surrounding the regex in `\\b`.\n #[test]\n fn word() {\n let matcher =\n RegexMatcherBuilder::new().word(true).build(r\"-2\").unwrap();\n assert!(matcher.is_match(b\"abc -2 foo\").unwrap());\n\n let matcher =\n RegexMatcherBuilder::new().word(false).build(r\"\\b-2\\b\").unwrap();\n assert!(!matcher.is_match(b\"abc -2 foo\").unwrap());\n }\n\n // Test that enabling a line terminator prevents it from matching through\n // said line terminator.\n #[test]\n fn line_terminator() {\n // This works, because there's no line terminator specified.\n let matcher = RegexMatcherBuilder::new().build(r\"abc\\sxyz\").unwrap();\n assert!(matcher.is_match(b\"abc\\nxyz\").unwrap());\n\n // This doesn't.\n let matcher = RegexMatcherBuilder::new()\n .line_terminator(Some(b'\\n'))\n .build(r\"abc\\sxyz\")\n .unwrap();\n assert!(!matcher.is_match(b\"abc\\nxyz\").unwrap());\n }\n\n // Ensure that the builder returns an error if a line terminator is set\n // and the regex could not be modified to remove a line terminator.\n #[test]\n fn line_terminator_error() {\n assert!(\n RegexMatcherBuilder::new()\n .line_terminator(Some(b'\\n'))\n .build(r\"a\\nz\")\n .is_err()\n )\n }\n\n // Test that enabling CRLF permits `$` to match at the end of a line.\n #[test]\n fn line_terminator_crlf() {\n // Test normal use of `$` with a `\\n` line terminator.\n let matcher = RegexMatcherBuilder::new()\n .multi_line(true)\n .build(r\"abc$\")\n .unwrap();\n assert!(matcher.is_match(b\"abc\\n\").unwrap());\n\n // Test that `$` doesn't match at `\\r\\n` boundary normally.\n let matcher = RegexMatcherBuilder::new()\n .multi_line(true)\n .build(r\"abc$\")\n .unwrap();\n assert!(!matcher.is_match(b\"abc\\r\\n\").unwrap());\n\n // Now check the CRLF handling.\n let matcher = RegexMatcherBuilder::new()\n .multi_line(true)\n .crlf(true)\n .build(r\"abc$\")\n .unwrap();\n assert!(matcher.is_match(b\"abc\\r\\n\").unwrap());\n }\n\n // Test that smart case works.\n #[test]\n fn case_smart() {\n let matcher =\n RegexMatcherBuilder::new().case_smart(true).build(r\"abc\").unwrap();\n assert!(matcher.is_match(b\"ABC\").unwrap());\n\n let matcher =\n RegexMatcherBuilder::new().case_smart(true).build(r\"aBc\").unwrap();\n assert!(!matcher.is_match(b\"ABC\").unwrap());\n }\n\n // Test that finding candidate lines works as expected.\n // FIXME: Re-enable this test once inner literal extraction works.\n #[test]\n #[ignore]\n fn candidate_lines() {\n fn is_confirmed(m: LineMatchKind) -> bool {\n match m {\n LineMatchKind::Confirmed(_) => true,\n _ => false,\n }\n }\n fn is_candidate(m: LineMatchKind) -> bool {\n match m {\n LineMatchKind::Candidate(_) => true,\n _ => false,\n }\n }\n\n // With no line terminator set, we can't employ any optimizations,\n // so we get a confirmed match.\n let matcher = RegexMatcherBuilder::new().build(r\"\\wfoo\\s\").unwrap();\n let m = matcher.find_candidate_line(b\"afoo \").unwrap().unwrap();\n assert!(is_confirmed(m));\n\n // With a line terminator and a regex specially crafted to have an\n // easy-to-detect inner literal, we can apply an optimization that\n // quickly finds candidate matches.\n let matcher = RegexMatcherBuilder::new()\n .line_terminator(Some(b'\\n'))\n .build(r\"\\wfoo\\s\")\n .unwrap();\n let m = matcher.find_candidate_line(b\"afoo \").unwrap().unwrap();\n assert!(is_candidate(m));\n }\n}", "messages": null, "tools": null} {"id": "a3a626e707aafddb", "category": "code", "domain": "code", "source": "flask", "license": "BSD-3-Clause", "license_url": "https://spdx.org/licenses/BSD-3-Clause.html", "path": "examples/tutorial/flaskr/templates/auth/login.html", "lang": "html", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/pallets/flask", "commit": "6a2f545bfd8ed31e19066a299296917e034aca58", "collector": "tools/harvest.py"}, "chars": 423, "sha256": "e0e93696d93ca3a9d110db182752270c8eea79586da80410a6441e42e93d77db", "text": "{% extends 'base.html' %}\n\n{% block header %}\n

{% block title %}Log In{% endblock %}

\n{% endblock %}\n\n{% block content %}\n
\n \n \n \n \n \n
\n{% endblock %}", "messages": null, "tools": null} {"id": "a3ba1389b0807b7e", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/hmr/hotData.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 394, "sha256": "787f46319fa45687059bb692349fdee719422c7d2a5af8a709c34b9bf9e20094", "text": "export const value = 1\n\nif (import.meta.hot) {\n const data = import.meta.hot.data\n if ('fromExecution' in data) {\n console.log(`(hot data) value from execution: ${data.fromExecution}`)\n console.log(`(hot data) value from dispose: ${data.fromDispose}`)\n }\n data.fromExecution = value\n\n import.meta.hot.dispose((data) => {\n data.fromDispose = value\n })\n import.meta.hot.accept()\n}", "messages": null, "tools": null} {"id": "a3de0b0e22e730c6", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/optimize-deps/unused-split-entry.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 510, "sha256": "58f4508d9ef8dc492b3bbe784a3ea1f3a1111e1b987aac91f549df327e0bc69d", "text": "import msg from '@vitejs/test-added-in-entries'\n\n// This is an entry file that is added to optimizeDeps.entries\n// When the deps aren't cached, these entries are also processed\n// to discover dependencies in them. This should only be needed\n// for code split sections that are commonly visited after\n// first load where a full-reload wants to be avoided at the expense\n// of extra processing on cold start. Another option is to add\n// the missing dependencies to optimizeDeps.include directly\n\nconsole.log(msg)", "messages": null, "tools": null} {"id": "a3e0c85c90b1b99f", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/nested-deps/index.html", "lang": "html", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 1457, "sha256": "ad6de5c93b718811a19f1eee928131e1b7b481d1b661d2e12db43cb9d9756ec5", "text": "

direct dependency A

\n
\n\n

direct dependency B

\n
\n\n

nested dependency A

\n
\n\n

direct dependency C

\n
\n\n

side dependency C

\n
\n\n

direct dependency D

\n
\n\n

nested dependency nested-D (dep of D)

\n
\n\n

exclude dependency of pre-bundled dependency

\n
nested module instance count:
\n\n

absolute dependency path:

\n\n

self referencing

\n
\n\n", "messages": null, "tools": null}
{"id": "a4081695c690c094", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/ssr-wasm/src/static-light.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 295, "sha256": "946c072d7a71a4dc370666a939f31a526fb7685322696a7931f6f00cc7f0f7fc", "text": "import light from './light.wasm?init'\n\nexport async function render() {\n  let result\n  const { exported_func } = await light({\n    imports: {\n      imported_func: (res) => (result = res),\n    },\n  }).then((i) => i.exports)\n  exported_func()\n  return `
${result}
`\n}", "messages": null, "tools": null} {"id": "a435aee2fe311209", "category": "code", "domain": "code", "source": "serde", "license": "MIT OR Apache-2.0", "license_url": "https://spdx.org/licenses/MIT.html", "path": "test_suite/tests/test_remote.rs", "lang": "rust", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/serde-rs/serde", "commit": "747814f7d5fbab872df3b02f070c165b91bde062", "collector": "tools/harvest.py"}, "chars": 5808, "sha256": "de68cb59cc525483474d179a48fa0c4dc88124c8a670fd9323c85a7543d0516f", "text": "#![allow(clippy::redundant_field_names, dead_code)]\n\nuse serde_derive::{Deserialize, Serialize};\n\nmod remote {\n pub struct Unit;\n\n pub struct PrimitivePriv(u8);\n\n #[allow(dead_code)]\n pub struct PrimitivePub(pub u8);\n\n pub struct NewtypePriv(Unit);\n\n #[allow(dead_code)]\n pub struct NewtypePub(pub Unit);\n\n pub struct TuplePriv(u8, Unit);\n\n #[allow(dead_code)]\n pub struct TuplePub(pub u8, pub Unit);\n\n pub struct StructPriv {\n a: u8,\n b: Unit,\n }\n\n #[allow(dead_code)]\n pub struct StructPub {\n pub a: u8,\n pub b: Unit,\n }\n\n impl PrimitivePriv {\n pub fn new(a: u8) -> Self {\n PrimitivePriv(a)\n }\n\n pub fn get(&self) -> u8 {\n self.0\n }\n }\n\n impl NewtypePriv {\n pub fn new(a: Unit) -> Self {\n NewtypePriv(a)\n }\n\n pub fn get(&self) -> &Unit {\n &self.0\n }\n }\n\n impl TuplePriv {\n pub fn new(a: u8, b: Unit) -> Self {\n TuplePriv(a, b)\n }\n\n pub fn first(&self) -> u8 {\n self.0\n }\n\n pub fn second(&self) -> &Unit {\n &self.1\n }\n }\n\n impl StructPriv {\n pub fn new(a: u8, b: Unit) -> Self {\n StructPriv { a: a, b: b }\n }\n\n pub fn a(&self) -> u8 {\n self.a\n }\n\n pub fn b(&self) -> &Unit {\n &self.b\n }\n }\n\n pub struct StructGeneric {\n pub value: T,\n }\n\n impl StructGeneric {\n #[allow(dead_code)]\n pub fn get_value(&self) -> &T {\n &self.value\n }\n }\n\n #[allow(dead_code)]\n pub enum EnumGeneric {\n Variant(T),\n }\n}\n\n#[derive(Serialize, Deserialize)]\n#[allow(dead_code)]\nstruct Test {\n #[serde(with = \"UnitDef\")]\n unit: remote::Unit,\n\n #[serde(with = \"PrimitivePrivDef\")]\n primitive_priv: remote::PrimitivePriv,\n\n #[serde(with = \"PrimitivePubDef\")]\n primitive_pub: remote::PrimitivePub,\n\n #[serde(with = \"NewtypePrivDef\")]\n newtype_priv: remote::NewtypePriv,\n\n #[serde(with = \"NewtypePubDef\")]\n newtype_pub: remote::NewtypePub,\n\n #[serde(with = \"TuplePrivDef\")]\n tuple_priv: remote::TuplePriv,\n\n #[serde(with = \"TuplePubDef\")]\n tuple_pub: remote::TuplePub,\n\n #[serde(with = \"StructPrivDef\")]\n struct_priv: remote::StructPriv,\n\n #[serde(with = \"StructPubDef\")]\n struct_pub: remote::StructPub,\n\n #[serde(with = \"StructConcrete\")]\n struct_concrete: remote::StructGeneric,\n\n #[serde(with = \"EnumConcrete\")]\n enum_concrete: remote::EnumGeneric,\n\n #[serde(with = \"ErrorKindDef\")]\n io_error_kind: ErrorKind,\n}\n\n#[derive(Serialize, Deserialize)]\n#[serde(remote = \"remote::Unit\")]\n#[allow(dead_code)]\nstruct UnitDef;\n\n#[derive(Serialize, Deserialize)]\n#[serde(remote = \"remote::PrimitivePriv\")]\nstruct PrimitivePrivDef(#[serde(getter = \"remote::PrimitivePriv::get\")] u8);\n\n#[derive(Serialize, Deserialize)]\n#[serde(remote = \"remote::PrimitivePub\")]\n#[allow(dead_code)]\nstruct PrimitivePubDef(u8);\n\n#[derive(Serialize, Deserialize)]\n#[serde(remote = \"remote::NewtypePriv\")]\nstruct NewtypePrivDef(#[serde(getter = \"remote::NewtypePriv::get\", with = \"UnitDef\")] remote::Unit);\n\n#[derive(Serialize, Deserialize)]\n#[serde(remote = \"remote::NewtypePub\")]\n#[allow(dead_code)]\nstruct NewtypePubDef(#[serde(with = \"UnitDef\")] remote::Unit);\n\n#[derive(Serialize, Deserialize)]\n#[serde(remote = \"remote::TuplePriv\")]\nstruct TuplePrivDef(\n #[serde(getter = \"remote::TuplePriv::first\")] u8,\n #[serde(getter = \"remote::TuplePriv::second\", with = \"UnitDef\")] remote::Unit,\n);\n\n#[derive(Serialize, Deserialize)]\n#[serde(remote = \"remote::TuplePub\")]\n#[allow(dead_code)]\nstruct TuplePubDef(u8, #[serde(with = \"UnitDef\")] remote::Unit);\n\n#[derive(Serialize, Deserialize)]\n#[serde(remote = \"remote::StructPriv\")]\nstruct StructPrivDef {\n #[serde(getter = \"remote::StructPriv::a\")]\n a: u8,\n\n #[serde(getter = \"remote::StructPriv::b\")]\n #[serde(with = \"UnitDef\")]\n b: remote::Unit,\n}\n\n#[derive(Serialize, Deserialize)]\n#[serde(remote = \"remote::StructPub\")]\n#[allow(dead_code)]\nstruct StructPubDef {\n a: u8,\n\n #[serde(with = \"UnitDef\")]\n b: remote::Unit,\n}\n\n#[derive(Serialize, Deserialize)]\n#[serde(remote = \"remote::StructGeneric\")]\nstruct StructGenericWithGetterDef {\n #[serde(getter = \"remote::StructGeneric::get_value\")]\n value: T,\n}\n\n#[derive(Serialize, Deserialize)]\n#[serde(remote = \"remote::StructGeneric\")]\n#[allow(dead_code)]\nstruct StructConcrete {\n value: u8,\n}\n\n#[derive(Serialize, Deserialize)]\n#[serde(remote = \"remote::EnumGeneric\")]\n#[allow(dead_code)]\nenum EnumConcrete {\n Variant(u8),\n}\n\n#[derive(Debug)]\n#[allow(dead_code)]\nenum ErrorKind {\n NotFound,\n PermissionDenied,\n #[allow(dead_code)]\n ConnectionRefused,\n}\n\n#[derive(Serialize, Deserialize)]\n#[serde(remote = \"ErrorKind\")]\n#[non_exhaustive]\n#[allow(dead_code)]\nenum ErrorKindDef {\n NotFound,\n PermissionDenied,\n // ...\n}\n\nimpl From for remote::PrimitivePriv {\n fn from(def: PrimitivePrivDef) -> Self {\n remote::PrimitivePriv::new(def.0)\n }\n}\n\nimpl From for remote::NewtypePriv {\n fn from(def: NewtypePrivDef) -> Self {\n remote::NewtypePriv::new(def.0)\n }\n}\n\nimpl From for remote::TuplePriv {\n fn from(def: TuplePrivDef) -> Self {\n remote::TuplePriv::new(def.0, def.1)\n }\n}\n\nimpl From for remote::StructPriv {\n fn from(def: StructPrivDef) -> Self {\n remote::StructPriv::new(def.a, def.b)\n }\n}\n\nimpl From> for remote::StructGeneric {\n fn from(def: StructGenericWithGetterDef) -> Self {\n remote::StructGeneric { value: def.value }\n }\n}", "messages": null, "tools": null} {"id": "a4c44ebc4c8f711c", "category": "code", "domain": "code", "source": "json-cpp", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "docs/mkdocs/docs/api/json_pointer/push_back.md", "lang": "markdown", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/nlohmann/json", "commit": "21af527e756435701f23e01aa8ea8dab6e050c90", "collector": "tools/harvest.py"}, "chars": 662, "sha256": "62ea0548324ec538485a590b7731b269b46908292e193b72621cb4008ff500cc", "text": "# nlohmann::json_pointer::push_back\n\n```cpp\nvoid push_back(const string_t& token);\n\nvoid push_back(string_t&& token);\n```\n\nAppend an unescaped token at the end of the reference pointer.\n\n## Parameters\n\n`token` (in)\n: token to add\n\n## Complexity\n\nAmortized constant.\n\n## Examples\n\n??? example\n\n The example shows the result of `push_back` for different JSON Pointers.\n \n ```cpp\n --8<-- \"examples/json_pointer__push_back.cpp\"\n ```\n \n Output:\n \n ```json\n --8<-- \"examples/json_pointer__push_back.output\"\n ```\n\n## Version history\n\n- Added in version 3.6.0.\n- Changed type of `token` to `string_t` in version 3.11.0.", "messages": null, "tools": null} {"id": "a4cc7f09d48e4016", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/multiple-entrypoints/entrypoints/a1.js", "lang": "javascript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 935, "sha256": "dce88503fc43e945d58f3c25bdef26848d4d813cbe1c206d84f3a1f25e75bc5f", "text": "import a2 from './a2'\nimport a3 from './a3'\nimport a4 from './a4'\nimport a5 from './a5'\nimport a6 from './a6'\nimport a7 from './a7'\nimport a8 from './a8'\nimport a9 from './a9'\nimport a10 from './a10'\nimport a11 from './a11'\nimport a12 from './a12'\nimport a13 from './a13'\nimport a14 from './a14'\nimport a15 from './a15'\nimport a16 from './a16'\nimport a17 from './a17'\nimport a18 from './a18'\nimport a19 from './a19'\nimport a20 from './a20'\nimport a21 from './a21'\nimport a22 from './a22'\nimport a23 from './a23'\nimport a24 from './a24'\n\nexport const that = () => import('./a0.js')\n\nexport function other() {\n return (\n a2() +\n a3() +\n a4() +\n a5() +\n a6() +\n a7() +\n a8() +\n a9() +\n a10() +\n a11() +\n a12() +\n a13() +\n a14() +\n a15() +\n a16() +\n a17() +\n a18() +\n a19() +\n a20() +\n a21() +\n a22() +\n a23() +\n a24()\n )\n}\n\nexport default function () {\n return 123\n}", "messages": null, "tools": null} {"id": "a4fb332240d9bbcb", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "playground/css/__tests__/same-file-name/css-same-file-name.spec.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 547, "sha256": "b0e18e28a4153721593a7d5b00f8e1024d9f84211d80d3502baaf176e7a99b4e", "text": "import { beforeEach, describe, expect, test } from 'vitest'\nimport { findAssetFile, isBuild, startDefaultServe } from '~utils'\n\nbeforeEach(async () => {\n await startDefaultServe()\n})\n\nfor (let i = 0; i < 5; i++) {\n describe.runIf(isBuild)('css files has same basename', () => {\n test('emit file name should consistent', () => {\n expect(findAssetFile('sub.css', 'same-file-name', '.')).toMatch(\n '.sub1-sub',\n )\n expect(findAssetFile('sub2.css', 'same-file-name', '.')).toMatch(\n '.sub2-sub',\n )\n })\n })\n}", "messages": null, "tools": null} {"id": "a50263dd18234790", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/plugin-legacy/src/__tests__/snippets.spec.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 2160, "sha256": "f88636f8c463baa61b60306c1fa241db4cce1a6c146bdcde4b7e82d5038da2e1", "text": "import { describe, expect, test } from 'vitest'\nimport type { ecmaVersion } from 'acorn'\nimport { parse } from 'acorn'\nimport {\n createModernChunkLegacyGuard,\n detectModernBrowserCode,\n detectModernBrowserDetector,\n dynamicFallbackInlineCode,\n safari10NoModuleFix,\n systemJSInlineCode,\n} from '../snippets'\n\nconst shouldFailVersions: ecmaVersion[] = []\nfor (let v = 2015; v <= 2019; v++) {\n shouldFailVersions.push(v as ecmaVersion)\n}\n\nconst shouldPassVersions: ecmaVersion[] = []\nfor (let v = 2020; v <= 2024; v++) {\n shouldPassVersions.push(v as ecmaVersion)\n}\n\nfor (const version of shouldFailVersions) {\n test(`detect code should not be able to be parsed with ES${version}`, () => {\n expect(() => {\n parse(detectModernBrowserDetector, {\n ecmaVersion: version,\n sourceType: 'module',\n })\n }).toThrow()\n })\n}\n\nfor (const version of shouldPassVersions) {\n test(`detect code should be able to be parsed with ES${version}`, () => {\n expect(() => {\n parse(detectModernBrowserDetector, {\n ecmaVersion: version,\n sourceType: 'module',\n })\n }).not.toThrow()\n })\n}\n\ndescribe('snippets are valid', () => {\n const codes = {\n safari10NoModuleFix,\n systemJSInlineCode,\n detectModernBrowserCode,\n dynamicFallbackInlineCode,\n }\n\n for (const [name, value] of Object.entries(codes)) {\n test(`${name} is valid JS`, () => {\n expect(() => {\n parse(value, {\n ecmaVersion: 'latest',\n sourceType: 'module',\n })\n }).not.toThrow()\n })\n }\n})\n\ndescribe('createModernChunkLegacyGuard', () => {\n // https://github.com/vitejs/vite/issues/22008\n test('generates unique data URLs for different chunk filenames', () => {\n const guard1 = createModernChunkLegacyGuard('assets/index-abc123.js')\n const guard2 = createModernChunkLegacyGuard('assets/chunk-def456.js')\n expect(guard1).not.toBe(guard2)\n })\n\n test('is valid JS', () => {\n const guard = createModernChunkLegacyGuard('assets/index-abc123.js')\n expect(() => {\n parse(guard, {\n ecmaVersion: 'latest',\n sourceType: 'module',\n })\n }).not.toThrow()\n })\n})", "messages": null, "tools": null} {"id": "a55b98ba97dba27f", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/node/nodeResolve.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 1209, "sha256": "bbbdf35e4cd4c48937763132a1492c2a56556a0e2ea560791b0dfc2b7b265819", "text": "import isModuleSyncConditionEnabled from '#module-sync-enabled'\nimport { DEFAULT_EXTENSIONS } from './constants'\nimport { tryNodeResolve } from './plugins/resolve'\nimport { nodeLikeBuiltins } from './utils'\n\nexport interface NodeResolveWithViteOptions {\n root: string\n isRequire?: boolean\n}\n\n/**\n * Resolve like Node.js using Vite's resolution algorithm with preconfigured options.\n */\nexport function nodeResolveWithVite(\n id: string,\n importer: string | undefined,\n options: NodeResolveWithViteOptions,\n): string | undefined {\n return tryNodeResolve(id, importer, {\n root: options.root,\n isBuild: true,\n isProduction: true,\n preferRelative: false,\n tryIndex: true,\n mainFields: [],\n conditions: [\n 'node',\n ...(isModuleSyncConditionEnabled ? ['module-sync'] : []),\n ],\n externalConditions: [],\n external: [],\n noExternal: [],\n dedupe: [],\n extensions: DEFAULT_EXTENSIONS,\n preserveSymlinks: false,\n tsconfigPaths: false,\n // Intentionally disable package cache for now as consumers don't need it\n packageCache: undefined,\n isRequire: options.isRequire,\n builtins: nodeLikeBuiltins,\n disableOptionalPeerDepHandling: true,\n })?.id\n}", "messages": null, "tools": null} {"id": "a55cce1bc6911dea", "category": "code", "domain": "code", "source": "vite", "license": "MIT", "license_url": "https://spdx.org/licenses/MIT.html", "path": "packages/vite/src/node/plugins/html.ts", "lang": "typescript", "origin": "repo_file", "synthetic": false, "render": "text", "reasoning_strength": "", "provenance": {"upstream": "https://github.com/vitejs/vite", "commit": "4f1411d2c82dd98cd725cea436cc0becd095cc2b", "collector": "tools/harvest.py"}, "chars": 56426, "sha256": "f9f652dbd7dc8f144319362ed7c7a737b2d2fb369e9f7d7f8a9c43ad0bce492b", "text": "import path from 'node:path'\nimport { URL } from 'node:url'\nimport type {\n OutputAsset,\n OutputBundle,\n OutputChunk,\n RollupError,\n SourceMapInput,\n} from 'rolldown'\nimport MagicString from 'magic-string'\nimport colors from 'picocolors'\nimport type {\n DefaultTreeAdapterMap,\n ErrorCodes,\n ParserError,\n Token,\n} from 'parse5'\nimport { stripLiteral } from 'strip-literal'\nimport escapeHtml from 'escape-html'\nimport type { MinimalPluginContextWithoutEnvironment, Plugin } from '../plugin'\nimport type { ViteDevServer } from '../server'\nimport {\n decodeURIIfPossible,\n encodeURIPath,\n generateCodeFrame,\n getHash,\n isCSSRequest,\n isDataUrl,\n isExternalUrl,\n normalizePath,\n partialEncodeURIPath,\n processSrcSet,\n removeLeadingSlash,\n unique,\n} from '../utils'\nimport type { ResolvedConfig, ResolvedEnvironmentOptions } from '../config'\nimport { checkPublicFile } from '../publicDir'\nimport { BUNDLED_DEV_CLIENT_FILENAME } from '../constants'\nimport { toOutputFilePathInHtml } from '../build'\nimport { resolveEnvPrefix } from '../env'\nimport { cleanUrl } from '../../shared/utils'\nimport { perEnvironmentState } from '../environment'\nimport { getNodeAssetAttributes } from '../assetSource'\nimport type { Logger } from '../logger'\nimport {\n assetUrlRE,\n getPublicAssetFilename,\n publicAssetUrlRE,\n urlToBuiltUrl,\n} from './asset'\nimport { cssBundleNameCache } from './css'\nimport { modulePreloadPolyfillId } from './modulePreloadPolyfill'\n\ninterface ScriptAssetsUrl {\n start: number\n end: number\n url: string\n}\n\nconst htmlProxyRE =\n /[?&]html-proxy=?(?:&inline-css)?(?:&style-attr)?&index=(\\d+)\\.(?:js|css)$/\nconst isHtmlProxyRE = /[?&]html-proxy\\b/\n\nconst inlineCSSRE = /__VITE_INLINE_CSS__([a-z\\d]{8}_\\d+)__/g\n// Do not allow preceding '.', but do allow preceding '...' for spread operations\nconst inlineImportRE =\n /(?]*type\\s*=\\s*(?:\"importmap\"|'importmap'|importmap)[^>]*>.*?<\\/script>/is\nconst moduleScriptRE =\n /[ \\t]*]*type\\s*=\\s*(?:\"module\"|'module'|module)[^>]*>/i\nconst modulePreloadLinkRE =\n /[ \\t]*]*rel\\s*=\\s*(?:\"modulepreload\"|'modulepreload'|modulepreload)[\\s\\S]*?>/i\nconst importMapAppendRE = new RegExp(\n [moduleScriptRE, modulePreloadLinkRE].map((r) => r.source).join('|'),\n 'i',\n)\n\nexport const isHTMLProxy = (id: string): boolean => isHtmlProxyRE.test(id)\n\nexport const isHTMLRequest = (request: string): boolean =>\n htmlLangRE.test(request)\n\n// HTML Proxy Caches are stored by config -> filePath -> index\nexport const htmlProxyMap: WeakMap<\n ResolvedConfig,\n Map<\n string,\n {\n code: string\n map?: SourceMapInput\n }[]\n >\n> = new WeakMap()\n\n// HTML Proxy Transform result are stored by config\n// `${hash(importer)}_${query.index}` -> transformed css code\n// PS: key like `hash(/vite/playground/assets/index.html)_1`)\nexport const htmlProxyResult: Map = new Map()\n\nexport function htmlInlineProxyPlugin(config: ResolvedConfig): Plugin {\n // Should do this when `constructor` rather than when `buildStart`,\n // `buildStart` will be triggered multiple times then the cached result will be emptied.\n // https://github.com/vitejs/vite/issues/6372\n htmlProxyMap.set(config, new Map())\n return {\n name: 'vite:html-inline-proxy',\n\n resolveId: {\n filter: { id: isHtmlProxyRE },\n handler(id) {\n return id\n },\n },\n\n load: {\n filter: { id: isHtmlProxyRE },\n handler(id) {\n const proxyMatch = htmlProxyRE.exec(id)\n if (proxyMatch) {\n const index = Number(proxyMatch[1])\n const file = cleanUrl(id)\n const url = file.replace(normalizePath(config.root), '')\n const result = htmlProxyMap.get(config)!.get(url)?.[index]\n if (result) {\n // set moduleSideEffects to keep the module even if `treeshake.moduleSideEffects=false` is set\n return { ...result, moduleSideEffects: true }\n } else {\n throw new Error(`No matching HTML proxy module found from ${id}`)\n }\n }\n },\n },\n }\n}\n\nexport function addToHTMLProxyCache(\n config: ResolvedConfig,\n filePath: string,\n index: number,\n result: { code: string; map?: SourceMapInput },\n): void {\n if (!htmlProxyMap.get(config)) {\n htmlProxyMap.set(config, new Map())\n }\n if (!htmlProxyMap.get(config)!.get(filePath)) {\n htmlProxyMap.get(config)!.set(filePath, [])\n }\n htmlProxyMap.get(config)!.get(filePath)![index] = result\n}\n\nexport function addToHTMLProxyTransformResult(\n hash: string,\n code: string,\n): void {\n htmlProxyResult.set(hash, code)\n}\n\n// Some `` elements should not be inlined in build. Excluding:\n// - `shortcut` : only valid for IE <9, use `icon`\n// - `mask-icon` : deprecated since Safari 12 (for pinned tabs)\n// - `apple-touch-icon-precomposed` : only valid for iOS <7 (for avoiding gloss effect)\nconst noInlineLinkRels = new Set([\n 'icon',\n 'apple-touch-icon',\n 'apple-touch-startup-image',\n 'manifest',\n])\n\nexport const isAsyncScriptMap: WeakMap<\n ResolvedConfig,\n Map\n> = new WeakMap()\n\nexport function nodeIsElement(\n node: DefaultTreeAdapterMap['node'],\n): node is DefaultTreeAdapterMap['element'] {\n return node.nodeName[0] !== '#'\n}\n\nfunction traverseNodes(\n node: DefaultTreeAdapterMap['node'],\n visitor: (node: DefaultTreeAdapterMap['node']) => void,\n) {\n if (node.nodeName === 'template') {\n node = (node as DefaultTreeAdapterMap['template']).content\n }\n visitor(node)\n if (\n nodeIsElement(node) ||\n node.nodeName === '#document' ||\n node.nodeName === '#document-fragment'\n ) {\n node.childNodes.forEach((childNode) => traverseNodes(childNode, visitor))\n }\n}\n\ntype ParseWarnings = Partial>\n\nexport async function traverseHtml(\n html: string,\n filePath: string,\n warn: Logger['warn'],\n visitor: (node: DefaultTreeAdapterMap['node']) => void,\n): Promise {\n // lazy load compiler\n const { parse, ErrorCodes } = await import('parse5')\n const warnings: ParseWarnings = {}\n const ast = parse(html, {\n scriptingEnabled: false, // parse inside
\n \n
\n \n \n \n

Connect with us

\n

Join the Vite community

\n \n
\n