Skip to content

Commit 92528c2

Browse files
committed
Support serialization of std::vector<bool>
1 parent adff8fe commit 92528c2

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

src/serialize.h

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -555,6 +555,7 @@ template<typename Stream, unsigned int N, typename T> inline void Unserialize(St
555555
* vectors of unsigned char are a special case and are intended to be serialized as a single opaque blob.
556556
*/
557557
template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, const unsigned char&);
558+
template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, const bool&);
558559
template<typename Stream, typename T, typename A, typename V> void Serialize_impl(Stream& os, const std::vector<T, A>& v, const V&);
559560
template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v);
560561
template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, const unsigned char&);
@@ -713,6 +714,18 @@ void Serialize_impl(Stream& os, const std::vector<T, A>& v, const unsigned char&
713714
os.write((char*)v.data(), v.size() * sizeof(T));
714715
}
715716

717+
template<typename Stream, typename T, typename A>
718+
void Serialize_impl(Stream& os, const std::vector<T, A>& v, const bool&)
719+
{
720+
// A special case for std::vector<bool>, as dereferencing
721+
// std::vector<bool>::const_iterator does not result in a const bool&
722+
// due to std::vector's special casing for bool arguments.
723+
WriteCompactSize(os, v.size());
724+
for (bool elem : v) {
725+
::Serialize(os, elem);
726+
}
727+
}
728+
716729
template<typename Stream, typename T, typename A, typename V>
717730
void Serialize_impl(Stream& os, const std::vector<T, A>& v, const V&)
718731
{

src/test/serialize_tests.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,14 @@ static bool isCanonicalException(const std::ios_base::failure& ex)
258258
return strcmp(expectedException.what(), ex.what()) == 0;
259259
}
260260

261+
BOOST_AUTO_TEST_CASE(vector_bool)
262+
{
263+
std::vector<uint8_t> vec1{1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1};
264+
std::vector<bool> vec2{1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1};
265+
266+
BOOST_CHECK(vec1 == std::vector<uint8_t>(vec2.begin(), vec2.end()));
267+
BOOST_CHECK(SerializeHash(vec1) == SerializeHash(vec2));
268+
}
261269

262270
BOOST_AUTO_TEST_CASE(noncanonical)
263271
{

0 commit comments

Comments
 (0)