cpp: Add is_zero() and explicit bool() for basic types

This commit is contained in:
Paweł Bylica 2019-07-22 14:47:44 +02:00
parent 635aebeb66
commit 18e6dabe73
No known key found for this signature in database
GPG Key ID: 7A0C037434FE77EF
2 changed files with 40 additions and 0 deletions

View File

@ -24,6 +24,9 @@ struct address : evmc_address
///
/// Initializes bytes to zeros if not other @p init value provided.
constexpr address(evmc_address init = {}) noexcept : evmc_address{init} {}
/// Explicit operator converting to bool.
constexpr inline explicit operator bool() const noexcept;
};
/// The fixed size array of 32 bytes for storing 256-bit EVM values.
@ -35,6 +38,9 @@ struct bytes32 : evmc_bytes32
///
/// Initializes bytes to zeros if not other @p init value provided.
constexpr bytes32(evmc_bytes32 init = {}) noexcept : evmc_bytes32{init} {}
/// Explicit operator converting to bool.
constexpr inline explicit operator bool() const noexcept;
};
/// Loads 64 bits / 8 bytes of data from the given @p bytes array in big-endian order.
@ -118,6 +124,28 @@ constexpr bool operator<(const bytes32& a, const bytes32& b) noexcept
load64be(&a.bytes[24]) < load64be(&b.bytes[24]));
}
/// Checks if the given address is the zero address.
constexpr inline bool is_zero(const address& a) noexcept
{
return a == address{};
}
constexpr address::operator bool() const noexcept
{
return !is_zero(*this);
}
/// Checks if the given bytes32 object has all zero bytes.
constexpr inline bool is_zero(const bytes32& a) noexcept
{
return a == bytes32{};
}
constexpr bytes32::operator bool() const noexcept
{
return !is_zero(*this);
}
/// @copydoc evmc_result
///

View File

@ -21,6 +21,9 @@ TEST(cpp, address)
{
evmc::address a;
EXPECT_EQ(std::count(std::begin(a.bytes), std::end(a.bytes), 0), sizeof(a));
EXPECT_TRUE(is_zero(a));
EXPECT_FALSE(a);
EXPECT_TRUE(!a);
auto other = evmc_address{};
other.bytes[19] = 0xfe;
@ -30,12 +33,18 @@ TEST(cpp, address)
a.bytes[0] = 1;
other = a;
EXPECT_TRUE(std::equal(std::begin(a.bytes), std::end(a.bytes), std::begin(other.bytes)));
EXPECT_FALSE(is_zero(a));
EXPECT_TRUE(a);
EXPECT_FALSE(!a);
}
TEST(cpp, bytes32)
{
evmc::bytes32 b;
EXPECT_EQ(std::count(std::begin(b.bytes), std::end(b.bytes), 0), sizeof(b));
EXPECT_TRUE(is_zero(b));
EXPECT_FALSE(b);
EXPECT_TRUE(!b);
auto other = evmc_bytes32{};
other.bytes[31] = 0xfe;
@ -45,6 +54,9 @@ TEST(cpp, bytes32)
b.bytes[0] = 1;
other = b;
EXPECT_TRUE(std::equal(std::begin(b.bytes), std::end(b.bytes), std::begin(other.bytes)));
EXPECT_FALSE(is_zero(b));
EXPECT_TRUE(b);
EXPECT_FALSE(!b);
}
TEST(cpp, std_hash)