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.
This commit is contained in:
Anthony Towns 2020-09-25 15:01:38 +10:00
parent 78f912c901
commit 183f308fff
3 changed files with 17 additions and 11 deletions

View file

@ -278,4 +278,10 @@ BOOST_AUTO_TEST_CASE( operator_with_self )
BOOST_CHECK(v == UintToArith256(uint256S("0"))); BOOST_CHECK(v == UintToArith256(uint256S("0")));
} }
BOOST_AUTO_TEST_CASE( check_ONE )
{
uint256 one = uint256S("0000000000000000000000000000000000000000000000000000000000000001");
BOOST_CHECK_EQUAL(one, uint256::ONE);
}
BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()

View file

@ -80,7 +80,4 @@ template std::string base_blob<256>::ToString() const;
template void base_blob<256>::SetHex(const char*); template void base_blob<256>::SetHex(const char*);
template void base_blob<256>::SetHex(const std::string&); template void base_blob<256>::SetHex(const std::string&);
uint256& UINT256_ONE() { const uint256 uint256::ONE(1);
static uint256* one = new uint256(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
return *one;
}

View file

@ -20,10 +20,11 @@ protected:
static constexpr int WIDTH = BITS / 8; static constexpr int WIDTH = BITS / 8;
uint8_t m_data[WIDTH]; uint8_t m_data[WIDTH];
public: public:
base_blob() /* construct 0 value by default */
{ constexpr base_blob() : m_data() {}
memset(m_data, 0, sizeof(m_data));
} /* constructor for constants between 1 and 255 */
constexpr explicit base_blob(uint8_t v) : m_data{v} {}
explicit base_blob(const std::vector<unsigned char>& vch); explicit base_blob(const std::vector<unsigned char>& vch);
@ -111,7 +112,7 @@ public:
*/ */
class uint160 : public base_blob<160> { class uint160 : public base_blob<160> {
public: public:
uint160() {} constexpr uint160() {}
explicit uint160(const std::vector<unsigned char>& vch) : base_blob<160>(vch) {} explicit uint160(const std::vector<unsigned char>& vch) : base_blob<160>(vch) {}
}; };
@ -122,8 +123,10 @@ public:
*/ */
class uint256 : public base_blob<256> { class uint256 : public base_blob<256> {
public: public:
uint256() {} constexpr uint256() {}
constexpr explicit uint256(uint8_t v) : base_blob<256>(v) {}
explicit uint256(const std::vector<unsigned char>& vch) : base_blob<256>(vch) {} explicit uint256(const std::vector<unsigned char>& vch) : base_blob<256>(vch) {}
static const uint256 ONE;
}; };
/* uint256 from const char *. /* uint256 from const char *.
@ -147,6 +150,6 @@ inline uint256 uint256S(const std::string& str)
return rv; return rv;
} }
uint256& UINT256_ONE(); inline const uint256& UINT256_ONE() { return uint256::ONE; }
#endif // BITCOIN_UINT256_H #endif // BITCOIN_UINT256_H