mirror of
https://github.com/zoriya/nitro.git
synced 2026-10-13 00:05:23 +00:00
53 lines
1.5 KiB
C++
53 lines
1.5 KiB
C++
//
|
|
// HybridContext.hpp
|
|
// Pods
|
|
//
|
|
// Created by Marc Rousavy on 17.07.24.
|
|
//
|
|
|
|
#pragma once
|
|
|
|
#include <memory>
|
|
#include "NitroLogger.hpp"
|
|
#include "TypeInfo.hpp"
|
|
|
|
namespace margelo::nitro {
|
|
|
|
class HybridObject;
|
|
|
|
/**
|
|
* Represents contextual state for a `HybridObject`.
|
|
*
|
|
* This can be used in remote implementations, e.g. in a Swift implementation
|
|
* to properly (weak-)reference the `HybridObject` instead of re-creating it each time.
|
|
*/
|
|
struct HybridContext final {
|
|
public:
|
|
std::weak_ptr<HybridObject> cppPart;
|
|
|
|
public:
|
|
template<typename THybridObject, typename TSwiftPart>
|
|
static inline std::shared_ptr<THybridObject> getOrCreate(TSwiftPart swiftPart) noexcept {
|
|
auto hybridContext = swiftPart.getHybridContext();
|
|
auto hybridObject = std::static_pointer_cast<THybridObject>(hybridContext.cppPart.lock());
|
|
if (hybridObject != nullptr) [[likely]] {
|
|
// Fast path - an existing HybridObject is still in cache! (HybridContext)
|
|
return hybridObject;
|
|
}
|
|
|
|
// Slow path - we need to create a new HybridObject that wraps our Swift implementation.
|
|
Logger::log(TAG, "Creating new HybridObject<%s> for %s...",
|
|
TypeInfo::getFriendlyTypename<THybridObject>(),
|
|
TypeInfo::getFriendlyTypename<TSwiftPart>());
|
|
hybridObject = std::make_shared<THybridObject>(std::forward<decltype(swiftPart)>(swiftPart));
|
|
hybridContext.cppPart = hybridObject;
|
|
swiftPart.setHybridContext(hybridContext);
|
|
return hybridObject;
|
|
}
|
|
|
|
private:
|
|
static constexpr auto TAG = "HybridContext";
|
|
};
|
|
|
|
} // namespace margelo::nitro
|