Skip to content

Commit f054bd0

Browse files
committed
refactor: use "if constexpr" in std::vector's Unserialize()
This gets rid of unnecessarily creating a temporary object T() to call the right function.
1 parent 088caa6 commit f054bd0

File tree

1 file changed

+15
-27
lines changed

1 file changed

+15
-27
lines changed

src/serialize.h

Lines changed: 15 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -650,8 +650,6 @@ template<typename Stream, unsigned int N, typename T> inline void Unserialize(St
650650
* vectors of unsigned char are a special case and are intended to be serialized as a single opaque blob.
651651
*/
652652
template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v);
653-
template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, const unsigned char&);
654-
template<typename Stream, typename T, typename A, typename V> void Unserialize_impl(Stream& is, std::vector<T, A>& v, const V&);
655653
template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v);
656654

657655
/**
@@ -801,35 +799,25 @@ void Serialize(Stream& os, const std::vector<T, A>& v)
801799
}
802800

803801

804-
template<typename Stream, typename T, typename A>
805-
void Unserialize_impl(Stream& is, std::vector<T, A>& v, const unsigned char&)
802+
template <typename Stream, typename T, typename A>
803+
void Unserialize(Stream& is, std::vector<T, A>& v)
806804
{
807-
// Limit size per read so bogus size value won't cause out of memory
808-
v.clear();
809-
unsigned int nSize = ReadCompactSize(is);
810-
unsigned int i = 0;
811-
while (i < nSize)
812-
{
813-
unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
814-
v.resize(i + blk);
815-
is.read(AsWritableBytes(Span{&v[i], blk}));
816-
i += blk;
805+
if constexpr (std::is_same_v<T, unsigned char>) {
806+
// Limit size per read so bogus size value won't cause out of memory
807+
v.clear();
808+
unsigned int nSize = ReadCompactSize(is);
809+
unsigned int i = 0;
810+
while (i < nSize) {
811+
unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
812+
v.resize(i + blk);
813+
is.read(AsWritableBytes(Span{&v[i], blk}));
814+
i += blk;
815+
}
816+
} else {
817+
Unserialize(is, Using<VectorFormatter<DefaultFormatter>>(v));
817818
}
818819
}
819820

820-
template<typename Stream, typename T, typename A, typename V>
821-
void Unserialize_impl(Stream& is, std::vector<T, A>& v, const V&)
822-
{
823-
Unserialize(is, Using<VectorFormatter<DefaultFormatter>>(v));
824-
}
825-
826-
template<typename Stream, typename T, typename A>
827-
inline void Unserialize(Stream& is, std::vector<T, A>& v)
828-
{
829-
Unserialize_impl(is, v, T());
830-
}
831-
832-
833821

834822
/**
835823
* pair

0 commit comments

Comments
 (0)