diff --git a/src/serialize.h b/src/serialize.h index 5cef72a9e03..2681b098a4e 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -24,6 +24,7 @@ #include #include #include +#include #include #include @@ -705,6 +706,12 @@ struct VectorFormatter template void Serialize(Stream& os, const std::basic_string& str); template void Unserialize(Stream& is, std::basic_string& str); +/** + * string_view + */ +template void Serialize(Stream& os, const std::basic_string_view& str); +template void Unserialize(Stream& is, std::basic_string_view& str) = delete; + /** * prevector */ @@ -807,7 +814,17 @@ void Unserialize(Stream& is, std::basic_string& str) is.read(MakeWritableByteSpan(str)); } - +/** + * string_view + */ +template +void Serialize(Stream& os, const std::basic_string_view& str) +{ + WriteCompactSize(os, str.size()); + if (!str.empty()) { + os.write(MakeByteSpan(str)); + } +} /** * prevector diff --git a/src/test/serialize_tests.cpp b/src/test/serialize_tests.cpp index f646ba5fafb..dd2c8cddcfc 100644 --- a/src/test/serialize_tests.cpp +++ b/src/test/serialize_tests.cpp @@ -241,6 +241,16 @@ BOOST_AUTO_TEST_CASE(noncanonical) BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException); } +BOOST_AUTO_TEST_CASE(string_view) +{ + const std::string_view sv{"hello, world"}; + DataStream ss; + ss << sv; + std::string s; + ss >> s; + BOOST_CHECK_EQUAL(sv, s); +} + BOOST_AUTO_TEST_CASE(class_methods) { int intval(100);