Commit 93173f5a authored by Aaryaman Sagar's avatar Aaryaman Sagar Committed by Facebook Github Bot

Backport std::bit_cast

Summary: Backport `std::bit_cast` from C++20.

Reviewed By: yfeldblum

Differential Revision: D13705428

fbshipit-source-id: a4b284563be67bec3fe4ddb54fed299650458d30
parent b1fd4e1a
...@@ -55,6 +55,7 @@ ...@@ -55,6 +55,7 @@
#include <folly/ConstexprMath.h> #include <folly/ConstexprMath.h>
#include <folly/Portability.h> #include <folly/Portability.h>
#include <folly/Traits.h>
#include <folly/Utility.h> #include <folly/Utility.h>
#include <folly/lang/Assume.h> #include <folly/lang/Assume.h>
#include <folly/portability/Builtins.h> #include <folly/portability/Builtins.h>
...@@ -374,4 +375,26 @@ T bitReverse(T n) { ...@@ -374,4 +375,26 @@ T bitReverse(T n) {
return static_cast<T>(Endian::swap(m)); return static_cast<T>(Endian::swap(m));
} }
#if __cpp_lib_bit_cast
using std::bit_cast;
#else
// mimic: std::bit_cast, C++20
template <
typename To,
typename From,
std::enable_if_t<
sizeof(From) == sizeof(To) && std::is_trivial<To>::value &&
is_trivially_copyable<From>::value,
int> = 0>
To bit_cast(const From& src) noexcept {
To to;
std::memcpy(&to, &src, sizeof(From));
return to;
}
#endif
} // namespace folly } // namespace folly
...@@ -25,7 +25,7 @@ ...@@ -25,7 +25,7 @@
#include <folly/portability/GTest.h> #include <folly/portability/GTest.h>
using namespace folly; namespace folly {
// Test constexpr-ness. // Test constexpr-ness.
#if !defined(__clang__) && !defined(_MSC_VER) #if !defined(__clang__) && !defined(_MSC_VER)
...@@ -231,3 +231,21 @@ TEST(Bits, PartialLoadUnaligned) { ...@@ -231,3 +231,21 @@ TEST(Bits, PartialLoadUnaligned) {
} }
} }
} }
TEST(Bits, BitCastBasic) {
auto one = std::make_unique<int>();
auto two = folly::bit_cast<std::uintptr_t>(one.get());
EXPECT_EQ(folly::bit_cast<int*>(two), one.get());
}
} // namespace folly
TEST(Bits, BitCastCompatibilityTest) {
using namespace folly;
using namespace std;
auto one = folly::Random::rand64();
auto pointer = bit_cast<std::uintptr_t>(one);
auto two = bit_cast<std::uint64_t>(pointer);
EXPECT_EQ(one, two);
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment