From 1b228b24a574aae0fb81e4a13ba40bfe45eb6dbd Mon Sep 17 00:00:00 2001 From: Jonathan G Rennison Date: Wed, 19 Jun 2024 19:50:48 +0100 Subject: [PATCH] Add helper wrappers similar to std::bit_cast which support size mismatches --- src/core/bit_cast.hpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/core/bit_cast.hpp b/src/core/bit_cast.hpp index 866cb397ff..8715d9c594 100644 --- a/src/core/bit_cast.hpp +++ b/src/core/bit_cast.hpp @@ -32,4 +32,28 @@ constexpr To bit_cast(const From& from) noexcept #endif +template +constexpr To bit_cast_to_storage(const From& from) noexcept +{ + static_assert(std::is_trivially_constructible_v); + static_assert(std::is_trivially_copyable_v); + static_assert(sizeof(To) >= sizeof(From)); + + To to{}; + memcpy(&to, &from, sizeof(From)); + return to; +} + +template +constexpr To bit_cast_from_storage(const From& from) noexcept +{ + static_assert(std::is_trivially_constructible_v); + static_assert(std::is_trivially_copyable_v); + static_assert(sizeof(To) <= sizeof(From)); + + To to{}; + memcpy(&to, &from, sizeof(To)); + return to; +} + #endif /* BIT_CAST_HPP */