diff options
Diffstat (limited to 'src/serialize.h')
-rw-r--r-- | src/serialize.h | 39 |
1 files changed, 37 insertions, 2 deletions
diff --git a/src/serialize.h b/src/serialize.h index f876efd9b5..2eb69b3ec0 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -334,8 +334,9 @@ I ReadVarInt(Stream& is) } } -#define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj))) -#define VARINT(obj) REF(WrapVarInt(REF(obj))) +#define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj))) +#define VARINT(obj) REF(WrapVarInt(REF(obj))) +#define LIMITED_STRING(obj,n) REF(LimitedString< n >(REF(obj))) /** Wrapper for serializing arrays and POD. */ @@ -398,6 +399,40 @@ public: } }; +template<size_t Limit> +class LimitedString +{ +protected: + std::string& string; +public: + LimitedString(std::string& string) : string(string) {} + + template<typename Stream> + void Unserialize(Stream& s, int, int=0) + { + 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[0], size); + } + + template<typename Stream> + void Serialize(Stream& s, int, int=0) const + { + WriteCompactSize(s, string.size()); + if (!string.empty()) + s.write((char*)&string[0], string.size()); + } + + unsigned int GetSerializeSize(int, int=0) const + { + return GetSizeOfCompactSize(string.size()) + string.size(); + } +}; + template<typename I> CVarInt<I> WrapVarInt(I& n) { return CVarInt<I>(n); } |