Convert LimitedString to formatter

This commit is contained in:
Pieter Wuille 2020-05-20 11:13:06 -07:00
parent ef17c03e07
commit 92beff15d3
2 changed files with 9 additions and 17 deletions

View File

@ -503,7 +503,7 @@ static inline Wrapper<Formatter, T&> Using(T&& t) { return Wrapper<Formatter, T&
#define VARINT_MODE(obj, mode) Using<VarIntFormatter<mode>>(obj)
#define VARINT(obj) Using<VarIntFormatter<VarIntMode::DEFAULT>>(obj)
#define COMPACTSIZE(obj) Using<CompactSizeFormatter>(obj)
#define LIMITED_STRING(obj,n) LimitedString< n >(REF(obj))
#define LIMITED_STRING(obj,n) Using<LimitedStringFormatter<n>>(obj)
/** Serialization wrapper class for integers in VarInt format. */
template<VarIntMode Mode>
@ -588,31 +588,23 @@ struct CompactSizeFormatter
};
template<size_t Limit>
class LimitedString
struct LimitedStringFormatter
{
protected:
std::string& string;
public:
explicit LimitedString(std::string& _string) : string(_string) {}
template<typename Stream>
void Unserialize(Stream& s)
void Unser(Stream& s, std::string& v)
{
size_t size = ReadCompactSize(s);
if (size > Limit) {
throw std::ios_base::failure("String length limit exceeded");
}
string.resize(size);
if (size != 0)
s.read((char*)string.data(), size);
v.resize(size);
if (size != 0) s.read((char*)v.data(), size);
}
template<typename Stream>
void Serialize(Stream& s) const
void Ser(Stream& s, const std::string& v)
{
WriteCompactSize(s, string.size());
if (!string.empty())
s.write((char*)string.data(), string.size());
s << v;
}
};

View File

@ -93,7 +93,7 @@ void test_one_input(const std::vector<uint8_t>& buffer)
{
CDataStream data_stream{SER_NETWORK, INIT_PROTO_VERSION};
std::string s;
LimitedString<10> limited_string = LIMITED_STRING(s, 10);
auto limited_string = LIMITED_STRING(s, 10);
data_stream << random_string_1;
try {
data_stream >> limited_string;
@ -108,7 +108,7 @@ void test_one_input(const std::vector<uint8_t>& buffer)
}
{
CDataStream data_stream{SER_NETWORK, INIT_PROTO_VERSION};
const LimitedString<10> limited_string = LIMITED_STRING(random_string_1, 10);
const auto limited_string = LIMITED_STRING(random_string_1, 10);
data_stream << limited_string;
std::string deserialized_string;
data_stream >> deserialized_string;