Skip to content

Commit

Permalink
keep robust solution to read values
Browse files Browse the repository at this point in the history
  • Loading branch information
drexlerd committed Aug 26, 2024
1 parent bf2e23f commit aa24682
Showing 1 changed file with 6 additions and 8 deletions.
14 changes: 6 additions & 8 deletions include/flatmemory/details/byte_buffer_utils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,20 +36,18 @@ namespace flatmemory
template<IsTriviallyCopyable T>
T read_value(const uint8_t* buf)
{
alignas(T) std::byte temp[sizeof(T)]; // Temporary aligned buffer
std::memcpy(temp, buf, sizeof(T)); // Copy the bytes into the aligned buffer
// Use placement new to safely construct the object
return *::new (temp) T(*reinterpret_cast<T*>(temp));
T value;
std::memcpy(&value, buf, sizeof(T));
return value;
}

/// @brief Read unaligned data.
template<IsTriviallyCopyable T>
T read_value(uint8_t* buf)
{
alignas(T) std::byte temp[sizeof(T)]; // Temporary aligned buffer
std::memcpy(temp, buf, sizeof(T)); // Copy the bytes into the aligned buffer
// Use placement new to safely construct the object
return *::new (temp) T(*reinterpret_cast<T*>(temp));
T value;
std::memcpy(&value, buf, sizeof(T));
return value;
}

/// @brief Write unaligned data.
Expand Down

0 comments on commit aa24682

Please sign in to comment.