Commit d7dbd254 authored by Giuseppe Ottaviano's avatar Giuseppe Ottaviano Committed by Facebook Github Bot

Relax bit_cast requirements

Summary: The standard only requires `To` to be trivially copyable, not trivial.

Reviewed By: yfeldblum

Differential Revision: D17916612

fbshipit-source-id: 80ae35672ea4664fe4204c8181ac6402065c4e03
parent 3b4a98dc
......@@ -77,13 +77,13 @@ template <
typename To,
typename From,
std::enable_if_t<
sizeof(From) == sizeof(To) && std::is_trivial<To>::value &&
sizeof(From) == sizeof(To) && is_trivially_copyable<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;
aligned_storage_for_t<To> storage;
std::memcpy(&storage, &src, sizeof(From));
return reinterpret_cast<To&>(storage);
}
#endif
......
......@@ -255,16 +255,25 @@ 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
struct FancyInt {
FancyInt() {
ADD_FAILURE() << "Default constructor should not be called by bit_cast";
}
TEST(Bits, BitCastCompatibilityTest) {
using namespace folly;
using namespace std;
int value;
};
int x = 5;
auto bi = folly::bit_cast<FancyInt>(x);
EXPECT_EQ(x, bi.value);
}
TEST(Bits, BitCastCompatibilityTest) {
auto one = folly::Random::rand64();
auto pointer = bit_cast<std::uintptr_t>(one);
auto two = bit_cast<std::uint64_t>(pointer);
auto pointer = folly::bit_cast<std::uintptr_t>(one);
auto two = folly::bit_cast<std::uint64_t>(pointer);
EXPECT_EQ(one, two);
}
} // namespace folly
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