From eff3e56902c515ecb50353cefe321cd9e504ead2 Mon Sep 17 00:00:00 2001 From: Benjamin Bannier Date: Fri, 10 Nov 2023 11:46:41 +0100 Subject: [PATCH] Add `to_string_for_print` for string literals. --- hilti/runtime/include/types/string.h | 8 ++++++++ hilti/runtime/src/tests/string.cc | 12 ++++++++++++ 2 files changed, 20 insertions(+) diff --git a/hilti/runtime/include/types/string.h b/hilti/runtime/include/types/string.h index 3b0a2a2cb..45c391fdb 100644 --- a/hilti/runtime/include/types/string.h +++ b/hilti/runtime/include/types/string.h @@ -77,5 +77,13 @@ inline std::string detail::to_string_for_print(const std::stri return escapeUTF8(x, false, false, true); } +// Specialization for string literals. Since `to_string_for_print` is not +// implemented with ADL like e.g., `to_string` provide an overload for string +// literals. This is needed since we cannot partially specialize +// `to_string_for_print`. +template +inline std::string to_string_for_print(const CharT (&x)[N]) { + return x; +} } // namespace hilti::rt diff --git a/hilti/runtime/src/tests/string.cc b/hilti/runtime/src/tests/string.cc index 5a6a5323f..c0ad60790 100644 --- a/hilti/runtime/src/tests/string.cc +++ b/hilti/runtime/src/tests/string.cc @@ -61,4 +61,16 @@ TEST_CASE("upper") { "illegal UTF8 sequence in string", const RuntimeError&); } +TEST_CASE("to_string") { + CHECK_EQ(to_string(std::string("abc")), "\"abc\""); + CHECK_EQ(to_string(std::string_view("abc")), "\"abc\""); + CHECK_EQ(to_string("abc"), "\"abc\""); +} + +TEST_CASE("to_string_for_print") { + CHECK_EQ(to_string_for_print(std::string("abc")), "abc"); + CHECK_EQ(to_string_for_print(std::string_view("abc")), "abc"); + CHECK_EQ(to_string_for_print("abc"), "abc"); +} + TEST_SUITE_END();