serialize: string_view serialization

Allows `stream << sv` to serialize from a string_view directly, without
converting to a string or similar first.
This commit is contained in:
Anthony Towns
2026-02-26 20:53:36 +10:00
parent 47da4f9b71
commit 1b3f776ebb
2 changed files with 28 additions and 1 deletions

View File

@@ -24,6 +24,7 @@
#include <set>
#include <span>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
@@ -705,6 +706,12 @@ struct VectorFormatter
template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str);
template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str);
/**
* string_view
*/
template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string_view<C>& str);
template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string_view<C>& str) = delete;
/**
* prevector
*/
@@ -807,7 +814,17 @@ void Unserialize(Stream& is, std::basic_string<C>& str)
is.read(MakeWritableByteSpan(str));
}
/**
* string_view
*/
template<typename Stream, typename C>
void Serialize(Stream& os, const std::basic_string_view<C>& str)
{
WriteCompactSize(os, str.size());
if (!str.empty()) {
os.write(MakeByteSpan(str));
}
}
/**
* prevector

View File

@@ -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);