-
Notifications
You must be signed in to change notification settings - Fork 24.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Summary: Pull Request resolved: #39358 This adds a function polyfilling C++ 20's `std::bit_cast`, using `memcpy()` to be safe with strict aliasing rules. This replaces the conditional code in CompactValue for type punning, an unsafe place in YGJNI where we do it unsafely, and is used in ValuePool. The polyfill can be switched to `std::bit_cast` whenever we adopt C++ 20. Note that this doesn't actually call into `memcpy()`, as verified by Godbolt. Compilers are aware of the memcpy type punning pattern and optimize it, but it's ugly and confusing to folks who haven't seen it before. Reviewed By: javache Differential Revision: D49082997 fbshipit-source-id: b848775a68286bdb11b2a3a95bef8069364ac9b5
- Loading branch information
1 parent
9dd654f
commit 8658bdc
Showing
3 changed files
with
39 additions
and
45 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
29 changes: 29 additions & 0 deletions
29
packages/react-native/ReactCommon/yoga/yoga/bits/BitCast.h
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
/* | ||
* Copyright (c) Meta Platforms, Inc. and affiliates. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
*/ | ||
|
||
#pragma once | ||
|
||
#include <cstring> | ||
#include <type_traits> | ||
|
||
namespace facebook::yoga { | ||
|
||
// Polyfill for std::bit_cast() from C++20, to allow safe type punning | ||
// https://en.cppreference.com/w/cpp/numeric/bit_cast | ||
template <class To, class From> | ||
std::enable_if_t< | ||
sizeof(To) == sizeof(From) && std::is_trivially_copyable_v<From> && | ||
std::is_trivially_copyable_v<To> && | ||
std::is_trivially_constructible_v<To>, | ||
To> | ||
bit_cast(const From& src) noexcept { | ||
To dst; | ||
std::memcpy(&dst, &src, sizeof(To)); | ||
return dst; | ||
} | ||
|
||
} // namespace facebook::yoga |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters