From 16be21339c48e46eddb29baf9cc280c269bc0e8e Mon Sep 17 00:00:00 2001 From: Brady Date: Tue, 8 Oct 2024 21:49:57 -0500 Subject: [PATCH] Fix undefined behavior in `scan_result_base::read` --- include/libhat/Scanner.hpp | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/include/libhat/Scanner.hpp b/include/libhat/Scanner.hpp index eef9ae5..33ec2c1 100644 --- a/include/libhat/Scanner.hpp +++ b/include/libhat/Scanner.hpp @@ -26,7 +26,16 @@ namespace hat { /// Reads an integer of the specified type located at an offset from the signature result template [[nodiscard]] constexpr Int read(size_t offset) const { - return *reinterpret_cast(this->result + offset); + if LIBHAT_IF_CONSTEVAL { + static constexpr size_t sz = sizeof(Int); + return std::bit_cast([=](std::index_sequence) { + return std::array{this->result + offset + Index...}; + }(std::make_index_sequence{})); + } else { + Int value; + std::memcpy(&value, this->result + offset, sizeof(Int)); + return value; + } } /// Reads an integer of the specified type which represents an index into an array with the given element type