Skip to content

Commit

Permalink
test: Use string_view for json_tests
Browse files Browse the repository at this point in the history
This avoids a static constructor of the global std::string, and rules
out possibly expensive and implicit copies of the string completely.
  • Loading branch information
MarcoFalke committed Sep 3, 2024
1 parent 9cb9651 commit fac9736
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 11 deletions.
8 changes: 5 additions & 3 deletions cmake/script/GenerateHeaderFromJson.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
file(READ ${JSON_SOURCE_PATH} hex_content HEX)
string(REGEX MATCHALL "([A-Za-z0-9][A-Za-z0-9])" bytes "${hex_content}")

file(WRITE ${HEADER_PATH} "#include <string>\n")
file(WRITE ${HEADER_PATH} "#include <string_view>\n")
file(APPEND ${HEADER_PATH} "namespace json_tests{\n")
get_filename_component(json_source_basename ${JSON_SOURCE_PATH} NAME_WE)
file(APPEND ${HEADER_PATH} "static const std::string ${json_source_basename}{\n")
file(APPEND ${HEADER_PATH} "inline constexpr char detail_${json_source_basename}_bytes[]{\n")

set(i 0)
foreach(byte ${bytes})
Expand All @@ -21,4 +21,6 @@ foreach(byte ${bytes})
endif()
endforeach()

file(APPEND ${HEADER_PATH} "\n};};")
file(APPEND ${HEADER_PATH} "\n};\n")
file(APPEND ${HEADER_PATH} "inline constexpr std::string_view ${json_source_basename}{std::begin(detail_${json_source_basename}_bytes), std::end(detail_${json_source_basename}_bytes)};")
file(APPEND ${HEADER_PATH} "\n}")
8 changes: 4 additions & 4 deletions src/test/util/json.cpp
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
// Copyright (c) 2023 The Bitcoin Core developers
// Copyright (c) 2023-present The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <test/util/json.h>

#include <string>
#include <univalue.h>
#include <util/check.h>

#include <univalue.h>
#include <string_view>

UniValue read_json(const std::string& jsondata)
UniValue read_json(std::string_view jsondata)
{
UniValue v;
Assert(v.read(jsondata) && v.isArray());
Expand Down
8 changes: 4 additions & 4 deletions src/test/util/json.h
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
// Copyright (c) 2023 The Bitcoin Core developers
// Copyright (c) 2023-present The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef BITCOIN_TEST_UTIL_JSON_H
#define BITCOIN_TEST_UTIL_JSON_H

#include <string>

#include <univalue.h>

UniValue read_json(const std::string& jsondata);
#include <string_view>

UniValue read_json(std::string_view jsondata);

#endif // BITCOIN_TEST_UTIL_JSON_H

0 comments on commit fac9736

Please sign in to comment.