Skip to content

Commit

Permalink
Convert LimitedString to formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
sipa authored and furszy committed Jul 3, 2021
1 parent f021897 commit 8c74c09
Showing 1 changed file with 10 additions and 19 deletions.
29 changes: 10 additions & 19 deletions src/serialize.h
Original file line number Diff line number Diff line change
Expand Up @@ -532,7 +532,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>
Expand Down Expand Up @@ -616,33 +616,24 @@ struct CompactSizeFormatter
}
};

template <size_t Limit>
class LimitedString
template<size_t Limit>
struct LimitedStringFormatter
{
protected:
std::string& string;

public:
LimitedString(std::string& _string) : string(_string) {}

template <typename Stream>
void Unserialize(Stream& s)
template<typename Stream>
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
template<typename Stream>
void Ser(Stream& s, const std::string& v)
{
WriteCompactSize(s, string.size());
if (!string.empty())
s.write((char*)string.data(), string.size());
s << v;
}
};

Expand Down

0 comments on commit 8c74c09

Please sign in to comment.