refactor: use "if constexpr" in prevector's Unserialize()

This gets rid of unnecessarily creating a temporary object T() to call
the right function.
This commit is contained in:
Martin Leitner-Ankerl
2023-08-02 19:51:55 +02:00
parent c8839ec5cd
commit 0fafaca4d3

View File

@@ -643,8 +643,6 @@ template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_st
* prevectors of unsigned char are a special case and are intended to be serialized as a single opaque blob. * prevectors of unsigned char are a special case and are intended to be serialized as a single opaque blob.
*/ */
template<typename Stream, unsigned int N, typename T> inline void Serialize(Stream& os, const prevector<N, T>& v); template<typename Stream, unsigned int N, typename T> inline void Serialize(Stream& os, const prevector<N, T>& v);
template<typename Stream, unsigned int N, typename T> void Unserialize_impl(Stream& is, prevector<N, T>& v, const unsigned char&);
template<typename Stream, unsigned int N, typename T, typename V> void Unserialize_impl(Stream& is, prevector<N, T>& v, const V&);
template<typename Stream, unsigned int N, typename T> inline void Unserialize(Stream& is, prevector<N, T>& v); template<typename Stream, unsigned int N, typename T> inline void Unserialize(Stream& is, prevector<N, T>& v);
/** /**
@@ -762,35 +760,25 @@ void Serialize(Stream& os, const prevector<N, T>& v)
} }
template<typename Stream, unsigned int N, typename T> template <typename Stream, unsigned int N, typename T>
void Unserialize_impl(Stream& is, prevector<N, T>& v, const unsigned char&) void Unserialize(Stream& is, prevector<N, T>& v)
{ {
// Limit size per read so bogus size value won't cause out of memory if constexpr (std::is_same_v<T, unsigned char>) {
v.clear(); // Limit size per read so bogus size value won't cause out of memory
unsigned int nSize = ReadCompactSize(is); v.clear();
unsigned int i = 0; unsigned int nSize = ReadCompactSize(is);
while (i < nSize) unsigned int i = 0;
{ while (i < nSize) {
unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T))); unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
v.resize_uninitialized(i + blk); v.resize_uninitialized(i + blk);
is.read(AsWritableBytes(Span{&v[i], blk})); is.read(AsWritableBytes(Span{&v[i], blk}));
i += blk; i += blk;
}
} else {
Unserialize(is, Using<VectorFormatter<DefaultFormatter>>(v));
} }
} }
template<typename Stream, unsigned int N, typename T, typename V>
void Unserialize_impl(Stream& is, prevector<N, T>& v, const V&)
{
Unserialize(is, Using<VectorFormatter<DefaultFormatter>>(v));
}
template<typename Stream, unsigned int N, typename T>
inline void Unserialize(Stream& is, prevector<N, T>& v)
{
Unserialize_impl(is, v, T());
}
/** /**
* vector * vector