Skip to content

Commit 183f308

Browse files
committedSep 28, 2020
uint256: Update constructors to c++11, make ONE static
Replace the memset with C++11 value/aggregate initialisation of the m_data array, which still ensures the unspecified values end up as zero-initialised. This then allows changing UINT256_ONE() from dynamically allocating an object, to a simpler referencing a static allocation.
1 parent 78f912c commit 183f308

File tree

3 files changed

+17
-11
lines changed

3 files changed

+17
-11
lines changed
 

‎src/test/uint256_tests.cpp

+6
Original file line numberDiff line numberDiff line change
@@ -278,4 +278,10 @@ BOOST_AUTO_TEST_CASE( operator_with_self )
278278
BOOST_CHECK(v == UintToArith256(uint256S("0")));
279279
}
280280

281+
BOOST_AUTO_TEST_CASE( check_ONE )
282+
{
283+
uint256 one = uint256S("0000000000000000000000000000000000000000000000000000000000000001");
284+
BOOST_CHECK_EQUAL(one, uint256::ONE);
285+
}
286+
281287
BOOST_AUTO_TEST_SUITE_END()

‎src/uint256.cpp

+1-4
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,4 @@ template std::string base_blob<256>::ToString() const;
8080
template void base_blob<256>::SetHex(const char*);
8181
template void base_blob<256>::SetHex(const std::string&);
8282

83-
uint256& UINT256_ONE() {
84-
static uint256* one = new uint256(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
85-
return *one;
86-
}
83+
const uint256 uint256::ONE(1);

‎src/uint256.h

+10-7
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,11 @@ class base_blob
2020
static constexpr int WIDTH = BITS / 8;
2121
uint8_t m_data[WIDTH];
2222
public:
23-
base_blob()
24-
{
25-
memset(m_data, 0, sizeof(m_data));
26-
}
23+
/* construct 0 value by default */
24+
constexpr base_blob() : m_data() {}
25+
26+
/* constructor for constants between 1 and 255 */
27+
constexpr explicit base_blob(uint8_t v) : m_data{v} {}
2728

2829
explicit base_blob(const std::vector<unsigned char>& vch);
2930

@@ -111,7 +112,7 @@ class base_blob
111112
*/
112113
class uint160 : public base_blob<160> {
113114
public:
114-
uint160() {}
115+
constexpr uint160() {}
115116
explicit uint160(const std::vector<unsigned char>& vch) : base_blob<160>(vch) {}
116117
};
117118

@@ -122,8 +123,10 @@ class uint160 : public base_blob<160> {
122123
*/
123124
class uint256 : public base_blob<256> {
124125
public:
125-
uint256() {}
126+
constexpr uint256() {}
127+
constexpr explicit uint256(uint8_t v) : base_blob<256>(v) {}
126128
explicit uint256(const std::vector<unsigned char>& vch) : base_blob<256>(vch) {}
129+
static const uint256 ONE;
127130
};
128131

129132
/* uint256 from const char *.
@@ -147,6 +150,6 @@ inline uint256 uint256S(const std::string& str)
147150
return rv;
148151
}
149152

150-
uint256& UINT256_ONE();
153+
inline const uint256& UINT256_ONE() { return uint256::ONE; }
151154

152155
#endif // BITCOIN_UINT256_H

0 commit comments

Comments
 (0)
Please sign in to comment.