Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C++: Refactor {address,bytes32} constructors #646

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
139 changes: 30 additions & 109 deletions include/evmc/evmc.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

#include <evmc/evmc.h>
#include <evmc/helpers.h>
#include <evmc/hex.hpp>

#include <functional>
#include <initializer_list>
Expand All @@ -30,34 +31,17 @@ struct address : evmc_address
/// Default and converting constructor.
///
/// Initializes bytes to zeros if not other @p init value provided.
constexpr address(evmc_address init = {}) noexcept : evmc_address{init} {}
inline constexpr address(evmc_address init = {}) noexcept : evmc_address{init} {}

/// Converting constructor from unsigned integer value.
///
/// This constructor assigns the @p v value to the last 8 bytes [12:19]
/// in big-endian order.
constexpr explicit address(uint64_t v) noexcept
: evmc_address{{0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
static_cast<uint8_t>(v >> 56),
static_cast<uint8_t>(v >> 48),
static_cast<uint8_t>(v >> 40),
static_cast<uint8_t>(v >> 32),
static_cast<uint8_t>(v >> 24),
static_cast<uint8_t>(v >> 16),
static_cast<uint8_t>(v >> 8),
static_cast<uint8_t>(v >> 0)}}
{}
inline constexpr explicit address(uint64_t v) noexcept : evmc_address{}
{
for (size_t i = sizeof(bytes) - sizeof(v); i < sizeof(bytes); ++i)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this better?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's just shorter.

bytes[i] = static_cast<uint8_t>(v >> (8 * (sizeof(bytes) - 1 - i)));
}

/// Explicit operator converting to bool.
inline constexpr explicit operator bool() const noexcept;
Expand All @@ -74,46 +58,17 @@ struct bytes32 : evmc_bytes32
/// Default and converting constructor.
///
/// Initializes bytes to zeros if not other @p init value provided.
constexpr bytes32(evmc_bytes32 init = {}) noexcept : evmc_bytes32{init} {}
inline constexpr bytes32(evmc_bytes32 init = {}) noexcept : evmc_bytes32{init} {}

/// Converting constructor from unsigned integer value.
///
/// This constructor assigns the @p v value to the last 8 bytes [24:31]
/// in big-endian order.
constexpr explicit bytes32(uint64_t v) noexcept
: evmc_bytes32{{0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
static_cast<uint8_t>(v >> 56),
static_cast<uint8_t>(v >> 48),
static_cast<uint8_t>(v >> 40),
static_cast<uint8_t>(v >> 32),
static_cast<uint8_t>(v >> 24),
static_cast<uint8_t>(v >> 16),
static_cast<uint8_t>(v >> 8),
static_cast<uint8_t>(v >> 0)}}
{}
inline constexpr explicit bytes32(uint64_t v) noexcept : evmc_bytes32{}
{
for (size_t i = sizeof(bytes) - sizeof(v); i < sizeof(bytes); ++i)
bytes[i] = static_cast<uint8_t>(v >> (8 * (sizeof(bytes) - 1 - i)));
}

/// Explicit operator converting to bool.
inline constexpr explicit operator bool() const noexcept;
Expand Down Expand Up @@ -280,71 +235,37 @@ inline constexpr bytes32::operator bool() const noexcept

namespace literals
{
namespace internal
{
constexpr int from_hex(char c) noexcept
{
return (c >= 'a' && c <= 'f') ? c - ('a' - 10) :
(c >= 'A' && c <= 'F') ? c - ('A' - 10) :
c - '0';
}

constexpr uint8_t byte(const char* s, size_t i) noexcept
{
return static_cast<uint8_t>((from_hex(s[2 * i]) << 4) | from_hex(s[2 * i + 1]));
}
/// Breaks compilation and reports error string in constexpr context.
inline void error([[maybe_unused]] const char* message) noexcept {}

/// Converts a raw literal into value of type T.
template <typename T>
T from_hex(const char*) noexcept;

template <>
constexpr bytes32 from_hex<bytes32>(const char* s) noexcept
constexpr T to(std::string_view s) noexcept
{
return {
{{byte(s, 0), byte(s, 1), byte(s, 2), byte(s, 3), byte(s, 4), byte(s, 5), byte(s, 6),
byte(s, 7), byte(s, 8), byte(s, 9), byte(s, 10), byte(s, 11), byte(s, 12), byte(s, 13),
byte(s, 14), byte(s, 15), byte(s, 16), byte(s, 17), byte(s, 18), byte(s, 19), byte(s, 20),
byte(s, 21), byte(s, 22), byte(s, 23), byte(s, 24), byte(s, 25), byte(s, 26), byte(s, 27),
byte(s, 28), byte(s, 29), byte(s, 30), byte(s, 31)}}};
}
if (s == "0")
return T{};

template <>
constexpr address from_hex<address>(const char* s) noexcept
{
return {
{{byte(s, 0), byte(s, 1), byte(s, 2), byte(s, 3), byte(s, 4), byte(s, 5), byte(s, 6),
byte(s, 7), byte(s, 8), byte(s, 9), byte(s, 10), byte(s, 11), byte(s, 12), byte(s, 13),
byte(s, 14), byte(s, 15), byte(s, 16), byte(s, 17), byte(s, 18), byte(s, 19)}}};
}
if (s[0] != '0' || s[1] != 'x')
error("literal must be in hexadecimal notation");

template <typename T, char... c>
constexpr T from_literal() noexcept
{
constexpr auto size = sizeof...(c);
constexpr char literal[] = {c...};
constexpr bool is_simple_zero = size == 1 && literal[0] == '0';
if (s.length() != 2 * sizeof(T) + 2)
error("literal must match the result type size");

static_assert(is_simple_zero || (literal[0] == '0' && literal[1] == 'x'),
"literal must be in hexadecimal notation");
static_assert(is_simple_zero || size == 2 * sizeof(T) + 2,
"literal must match the result type size");

return is_simple_zero ? T{} : from_hex<T>(&literal[2]);
T r{};
internal::from_hex(s, r.bytes);
return r;
}
} // namespace internal

/// Literal for evmc::address.
template <char... c>
constexpr address operator""_address() noexcept
constexpr address operator""_address(const char* s) noexcept
{
return internal::from_literal<address, c...>();
return to<address>(s);
}

/// Literal for evmc::bytes32.
template <char... c>
constexpr bytes32 operator""_bytes32() noexcept
constexpr bytes32 operator""_bytes32(const char* s) noexcept
{
return internal::from_literal<bytes32, c...>();
return to<bytes32>(s);
}
} // namespace literals

Expand Down
125 changes: 88 additions & 37 deletions include/evmc/hex.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@

#include <cstdint>
#include <iterator>
#include <optional>
#include <string>
#include <string_view>
#include <system_error>

namespace evmc
{
Expand All @@ -17,55 +17,106 @@ using bytes = std::basic_string<uint8_t>;
/// String view of uint8_t chars.
using bytes_view = std::basic_string_view<uint8_t>;

/// Hex decoding error codes.
enum class hex_errc
{
/// Invalid hex digit encountered during decoding.
invalid_hex_digit = 1,

/// Input contains incomplete hex byte (length is odd).
incomplete_hex_byte_pair = 2,
};
/// Encode a byte to a hex string.
inline std::string hex(uint8_t b) noexcept
{
static constexpr auto hex_digits = "0123456789abcdef";
return {hex_digits[b >> 4], hex_digits[b & 0xf]};
}

/// Obtains a reference to the static error category object for hex errors.
const std::error_category& hex_category() noexcept;
/// Encodes bytes as hex string.
inline std::string hex(bytes_view bs)
{
std::string str;
str.reserve(bs.size() * 2);
for (const auto b : bs)
str += hex(b);
return str;
}

/// Creates error_code object out of a hex error code value.
inline std::error_code make_error_code(hex_errc errc) noexcept
namespace internal
{
/// Extracts the nibble value out of a hex digit.
/// Returns -1 in case of invalid hex digit.
inline constexpr int from_hex_digit(char h) noexcept
{
return {static_cast<int>(errc), hex_category()};
if (h >= '0' && h <= '9')
return h - '0';
else if (h >= 'a' && h <= 'f')
return h - 'a' + 10;
else if (h >= 'A' && h <= 'F')
return h - 'A' + 10;
else
return -1;
}

/// Hex decoding exception.
struct hex_error : std::system_error
/// The constexpr variant of std::isspace().
inline constexpr bool isspace(char ch) noexcept
{
using system_error::system_error;
};
// Implementation taken from LLVM's libc.
return ch == ' ' || (static_cast<unsigned>(ch) - '\t') < 5;
}

/// Encode a byte to a hex string.
inline std::string hex(uint8_t b) noexcept
template <typename OutputIt>
inline constexpr bool from_hex(std::string_view hex, OutputIt result) noexcept
{
static constexpr auto hex_chars = "0123456789abcdef";
return {hex_chars[b >> 4], hex_chars[b & 0xf]};
// Omit the optional 0x prefix.
if (hex.size() >= 2 && hex[0] == '0' && hex[1] == 'x')
hex.remove_prefix(2);

constexpr int empty_mark = -1;
int hi_nibble = empty_mark;
for (const auto h : hex)
{
if (isspace(h))
continue;

const int v = from_hex_digit(h);
if (v < 0)
return false;

if (hi_nibble == empty_mark)
{
hi_nibble = v << 4;
}
else
{
*result++ = static_cast<uint8_t>(hi_nibble | v);
hi_nibble = empty_mark;
}
}

return hi_nibble == empty_mark;
}
} // namespace internal

/// Validates hex encoded string.
std::error_code validate_hex(std::string_view hex) noexcept;

/// Decodes hex encoded string to bytes.
///
/// Throws hex_error with the appropriate error code.
bytes from_hex(std::string_view hex);
/// @return True if the input is valid hex.
inline bool validate_hex(std::string_view hex) noexcept
{
struct noop_output_iterator
{
uint8_t sink = {};
uint8_t& operator*() noexcept { return sink; }
noop_output_iterator operator++(int) noexcept { return *this; } // NOLINT(cert-dcl21-cpp)
};

/// Encodes bytes as hex string.
std::string hex(bytes_view bs);
} // namespace evmc
return internal::from_hex(hex, noop_output_iterator{});
}

namespace std
/// Decodes hex encoded string to bytes.
///
/// In case the input is invalid the returned value is std::nullopt.
/// This can happen if a non-hex digit or odd number of digits is encountered.
/// Whitespace in the input is ignored.
inline std::optional<bytes> from_hex(std::string_view hex)
{
/// Template specialization of std::is_error_code_enum for evmc::hex_errc.
/// This enabled implicit conversions from evmc::hex_errc to std::error_code.
template <>
struct is_error_code_enum<evmc::hex_errc> : true_type
{};
} // namespace std
bytes bs;
bs.reserve(hex.size() / 2);
if (!internal::from_hex(hex, std::back_inserter(bs)))
return {};
return bs;
}
} // namespace evmc
1 change: 0 additions & 1 deletion lib/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ target_compile_features(evmc_cpp INTERFACE cxx_std_17)
target_include_directories(evmc_cpp INTERFACE $<BUILD_INTERFACE:${EVMC_INCLUDE_DIR}>$<INSTALL_INTERFACE:include>)
target_link_libraries(evmc_cpp INTERFACE evmc::evmc)

add_subdirectory(hex)
add_subdirectory(instructions)
add_subdirectory(loader)
add_subdirectory(mocked_host)
Expand Down
18 changes: 0 additions & 18 deletions lib/hex/CMakeLists.txt

This file was deleted.

Loading