Add a BinaryTreeNode example for Cxx TMs (#41767)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/41767

Changelog: [Internal]

Adds a simple example showing a direct recursive node in a Cxx TM.

Currently we can't auto-generate [the necessary C++ Types](https://reactnative.dev/docs/next/the-new-architecture/cxx-custom-types#struct-generator) - but we can add it later if this scenarios becomes really common.

Direct recursive nodes, can't be value types - it would require infinite memory. Hence they are nullable and managed by a smart pointer.

Reviewed By: rshest

Differential Revision: D51784136

fbshipit-source-id: f6f0710d03583bdf1e6e72ba42d8df7f8ff8d915
This commit is contained in:
Christoph Purrer
2023-12-04 05:54:50 -08:00
committed by Facebook GitHub Bot
parent 5754b4a123
commit ead73de464
12 changed files with 322 additions and 5 deletions
@@ -91,6 +91,50 @@ struct CustomHostObjectRef {
using CustomHostObject = HostObjectWrapper<CustomHostObjectRef>;
#pragma mark - recursive objects
struct BinaryTreeNode {
std::unique_ptr<BinaryTreeNode> left;
int32_t value;
std::unique_ptr<BinaryTreeNode> right;
};
template <>
struct Bridging<BinaryTreeNode> {
static BinaryTreeNode fromJs(
jsi::Runtime& rt,
const jsi::Object& value,
const std::shared_ptr<CallInvoker>& jsInvoker) {
BinaryTreeNode result{
value.hasProperty(rt, "left")
? std::make_unique<BinaryTreeNode>(bridging::fromJs<BinaryTreeNode>(
rt, value.getProperty(rt, "left"), jsInvoker))
: nullptr,
bridging::fromJs<int32_t>(
rt, value.getProperty(rt, "value"), jsInvoker),
value.hasProperty(rt, "right")
? std::make_unique<BinaryTreeNode>(bridging::fromJs<BinaryTreeNode>(
rt, value.getProperty(rt, "right"), jsInvoker))
: nullptr};
return result;
}
static jsi::Object toJs(
jsi::Runtime& rt,
const BinaryTreeNode& value,
const std::shared_ptr<CallInvoker>& jsInvoker) {
auto result = facebook::jsi::Object(rt);
if (value.left) {
result.setProperty(
rt, "left", bridging::toJs(rt, *value.left, jsInvoker));
}
result.setProperty(rt, "value", bridging::toJs(rt, value.value, jsInvoker));
if (value.right) {
result.setProperty(
rt, "right", bridging::toJs(rt, *value.right, jsInvoker));
}
return result;
}
};
struct GraphNode {
std::string label;
std::optional<std::vector<GraphNode>> neighbors;
@@ -156,6 +200,8 @@ class NativeCxxModuleExample
jsi::Runtime& rt,
std::shared_ptr<CustomHostObject> arg);
BinaryTreeNode getBinaryTreeNode(jsi::Runtime& rt, BinaryTreeNode arg);
GraphNode getGraphNode(jsi::Runtime& rt, GraphNode arg);
NativeCxxModuleExampleCxxEnumFloat getNumEnum(