Browse Source

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.
pheonix 1 year ago
parent
commit
e5d5d0b7c6
2 changed files with 14 additions and 0 deletions
  1. 4 0
      include/bx/bx.h
  2. 10 0
      include/bx/inline/bx.inl

+ 4 - 0
include/bx/bx.h

@@ -214,6 +214,10 @@ namespace bx
 	template<typename Ty>
 	template<typename Ty>
 	constexpr bool isPowerOf2(Ty _a);
 	constexpr bool isPowerOf2(Ty _a);
 
 
+	/// Returns a value of type To by reinterpreting the object representation of From.
+	template <typename To, typename From>
+	constexpr To bit_cast(const From& value) noexcept;
+
 	/// Copy memory block.
 	/// Copy memory block.
 	///
 	///
 	/// @param _dst Destination pointer.
 	/// @param _dst Destination pointer.

+ 10 - 0
include/bx/inline/bx.inl

@@ -147,4 +147,14 @@ namespace bx
 		return _a && !(_a & (_a - 1) );
 		return _a && !(_a & (_a - 1) );
 	}
 	}
 
 
+	template <typename To, typename From>
+	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<To>(), "Destination target must be trivially constructible.");
+		To result;
+		bx::memCopy(&result, &value, sizeof(To));
+		return result;
+	}
+
 } // namespace bx
 } // namespace bx