Skip to content

Commit d5d1425

Browse files
committed
Bug fix: CDataStream::GetAndClear() when nReadPos > 0
Changed CDataStream::GetAndClear() to use the most obvious get get and clear instead of a tricky swap(). Added a unit test for CDataStream insert/erase/GetAndClear. Note: GetAndClear() is not performance critical, it is used only by the send-a-message-to-the-network code. Bug was not noticed before now because the send-a-message code never erased from the stream.
1 parent cd1fc24 commit d5d1425

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

src/serialize.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1104,8 +1104,8 @@ class CDataStream
11041104
}
11051105

11061106
void GetAndClear(CSerializeData &data) {
1107-
vch.swap(data);
1108-
CSerializeData().swap(vch);
1107+
data.insert(data.end(), begin(), end());
1108+
clear();
11091109
}
11101110
};
11111111

src/test/serialize_tests.cpp

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,4 +102,52 @@ BOOST_AUTO_TEST_CASE(noncanonical)
102102
BOOST_CHECK_EXCEPTION(ReadCompactSize(ss), std::ios_base::failure, isCanonicalException);
103103
}
104104

105+
BOOST_AUTO_TEST_CASE(insert_delete)
106+
{
107+
// Test inserting/deleting bytes.
108+
CDataStream ss(SER_DISK, 0);
109+
BOOST_CHECK_EQUAL(ss.size(), 0);
110+
111+
ss.write("\x00\x01\x02\xff", 4);
112+
BOOST_CHECK_EQUAL(ss.size(), 4);
113+
114+
char c = (char)11;
115+
116+
// Inserting at beginning/end/middle:
117+
ss.insert(ss.begin(), c);
118+
BOOST_CHECK_EQUAL(ss.size(), 5);
119+
BOOST_CHECK_EQUAL(ss[0], c);
120+
BOOST_CHECK_EQUAL(ss[1], 0);
121+
122+
ss.insert(ss.end(), c);
123+
BOOST_CHECK_EQUAL(ss.size(), 6);
124+
BOOST_CHECK_EQUAL(ss[4], (char)0xff);
125+
BOOST_CHECK_EQUAL(ss[5], c);
126+
127+
ss.insert(ss.begin()+2, c);
128+
BOOST_CHECK_EQUAL(ss.size(), 7);
129+
BOOST_CHECK_EQUAL(ss[2], c);
130+
131+
// Delete at beginning/end/middle
132+
ss.erase(ss.begin());
133+
BOOST_CHECK_EQUAL(ss.size(), 6);
134+
BOOST_CHECK_EQUAL(ss[0], 0);
135+
136+
ss.erase(ss.begin()+ss.size()-1);
137+
BOOST_CHECK_EQUAL(ss.size(), 5);
138+
BOOST_CHECK_EQUAL(ss[4], (char)0xff);
139+
140+
ss.erase(ss.begin()+1);
141+
BOOST_CHECK_EQUAL(ss.size(), 4);
142+
BOOST_CHECK_EQUAL(ss[0], 0);
143+
BOOST_CHECK_EQUAL(ss[1], 1);
144+
BOOST_CHECK_EQUAL(ss[2], 2);
145+
BOOST_CHECK_EQUAL(ss[3], (char)0xff);
146+
147+
// Make sure GetAndClear does the right thing:
148+
CSerializeData d;
149+
ss.GetAndClear(d);
150+
BOOST_CHECK_EQUAL(ss.size(), 0);
151+
}
152+
105153
BOOST_AUTO_TEST_SUITE_END()

0 commit comments

Comments
 (0)