Skip to content

Commit 4781813

Browse files
committed
Merge #12537: [arith_uint256] Make it safe to use "self" in operators
b120f7b [test] Add tests for self usage in arith_uint256 (Karl-Johan Alm) 08b17de [arith_uint256] Do not destroy *this content if passed-in operator may reference it (Karl-Johan Alm) Pull request description: Before this fix (see test commit), `v *= v` would result in `0` because `operator*=` set `*this` (`==b`) to `0` at the start. This patch changes the code to use `a` as temporary for `*this`~~, with drawback that `*this` is set to `a` at the end, an extra `=` operation in other words~~. Tree-SHA512: 8028a99880c3198a39c4bcc5056169735ba960625d553e15c0317510a52940c875f7a1fefe14e1af7fcf10c07a246411994a328cb1507bf3eaf1b6e7425390dc
2 parents 27278df + b120f7b commit 4781813

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

src/arith_uint256.cpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -69,16 +69,16 @@ base_uint<BITS>& base_uint<BITS>::operator*=(uint32_t b32)
6969
template <unsigned int BITS>
7070
base_uint<BITS>& base_uint<BITS>::operator*=(const base_uint& b)
7171
{
72-
base_uint<BITS> a = *this;
73-
*this = 0;
72+
base_uint<BITS> a;
7473
for (int j = 0; j < WIDTH; j++) {
7574
uint64_t carry = 0;
7675
for (int i = 0; i + j < WIDTH; i++) {
77-
uint64_t n = carry + pn[i + j] + (uint64_t)a.pn[j] * b.pn[i];
78-
pn[i + j] = n & 0xffffffff;
76+
uint64_t n = carry + a.pn[i + j] + (uint64_t)pn[j] * b.pn[i];
77+
a.pn[i + j] = n & 0xffffffff;
7978
carry = n >> 32;
8079
}
8180
}
81+
*this = a;
8282
return *this;
8383
}
8484

src/test/uint256_tests.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,4 +266,17 @@ BOOST_AUTO_TEST_CASE( conversion )
266266
BOOST_CHECK(R2L.GetHex() == UintToArith256(R2L).GetHex());
267267
}
268268

269+
BOOST_AUTO_TEST_CASE( operator_with_self )
270+
{
271+
arith_uint256 v = UintToArith256(uint256S("02"));
272+
v *= v;
273+
BOOST_CHECK(v == UintToArith256(uint256S("04")));
274+
v /= v;
275+
BOOST_CHECK(v == UintToArith256(uint256S("01")));
276+
v += v;
277+
BOOST_CHECK(v == UintToArith256(uint256S("02")));
278+
v -= v;
279+
BOOST_CHECK(v == UintToArith256(uint256S("0")));
280+
}
281+
269282
BOOST_AUTO_TEST_SUITE_END()

0 commit comments

Comments
 (0)