From e5d5d0b7c6f49025b98e9afbcc504af0528de132 Mon Sep 17 00:00:00 2001 From: pheonix Date: Sun, 28 Jan 2024 19:40:33 -0800 Subject: [PATCH] Add bx::bit_cast method (#316) This function provides the bx equivalent of std::bit_cast, in that it obtains a value of type To by reinterpreting the object representation of From using the memcpy aliasing method. --- include/bx/bx.h | 4 ++++ include/bx/inline/bx.inl | 10 ++++++++++ 2 files changed, 14 insertions(+) diff --git a/include/bx/bx.h b/include/bx/bx.h index 4877f56..79eff13 100644 --- a/include/bx/bx.h +++ b/include/bx/bx.h @@ -214,6 +214,10 @@ namespace bx template constexpr bool isPowerOf2(Ty _a); + /// Returns a value of type To by reinterpreting the object representation of From. + template + constexpr To bit_cast(const From& value) noexcept; + /// Copy memory block. /// /// @param _dst Destination pointer. diff --git a/include/bx/inline/bx.inl b/include/bx/inline/bx.inl index 80f7194..46c6c7e 100644 --- a/include/bx/inline/bx.inl +++ b/include/bx/inline/bx.inl @@ -147,4 +147,14 @@ namespace bx return _a && !(_a & (_a - 1) ); } + template + inline constexpr To bit_cast(const From& value) noexcept + { + BX_STATIC_ASSERT(sizeof(To) == sizeof(From), "To and From must be the same size."); + BX_STATIC_ASSERT(isTriviallyConstructible(), "Destination target must be trivially constructible."); + To result; + bx::memCopy(&result, &value, sizeof(To)); + return result; + } + } // namespace bx