// // HybridContext.hpp // Pods // // Created by Marc Rousavy on 17.07.24. // #pragma once #include #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 cppPart; public: template static inline std::shared_ptr getOrCreate(TSwiftPart swiftPart) noexcept { auto hybridContext = swiftPart.getHybridContext(); auto hybridObject = std::static_pointer_cast(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(), TypeInfo::getFriendlyTypename()); hybridObject = std::make_shared(std::forward(swiftPart)); hybridContext.cppPart = hybridObject; swiftPart.setHybridContext(hybridContext); return hybridObject; } private: static constexpr auto TAG = "HybridContext"; }; } // namespace margelo::nitro