From 718ffe5038e9dc38a9b100cddd4a7dd484ab1b69 Mon Sep 17 00:00:00 2001 From: Valentin Shergin Date: Mon, 29 Apr 2019 21:17:39 -0700 Subject: [PATCH] Fabric: `ContextContainer::findInstance` returns an optional intead of throwing an exception Summary: Sometimes we don't know for sure if `ContextContainer` has a value or not (and that's perfectly legit use case). In those cases now we can use `findInstance` method that returns an optional intead of throwing an exeption. Reviewed By: JoshuaGross Differential Revision: D15039137 fbshipit-source-id: 95ba8cc7b76e37d1bd17e18c0098e56350ff3fef --- ReactCommon/utils/ContextContainer.h | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/ReactCommon/utils/ContextContainer.h b/ReactCommon/utils/ContextContainer.h index b26f3106d..623de4be9 100644 --- a/ReactCommon/utils/ContextContainer.h +++ b/ReactCommon/utils/ContextContainer.h @@ -51,6 +51,7 @@ class ContextContainer final { /* * Returns a previously registered instance of the particular type `T` * for `key`. + * Throws an exception if the instance could not be found. */ template T getInstance(std::string const &key) const { @@ -65,6 +66,27 @@ class ContextContainer final { return *std::static_pointer_cast(instances_.at(key)); } + /* + * Returns a (wrapped in an optional) previously registered instance of + * the particular type `T` for given `key`. + * Returns an empty optional if the instance could not be found. + */ + template + better::optional findInstance(std::string const &key) const { + std::shared_lock lock(mutex_); + + auto iterator = instances_.find(key); + if (iterator == instances_.end()) { + return {}; + } + + assert( + typeHashes_.at(key) == typeid(T).hash_code() && + "ContextContainer stores an instance of different type for given key."); + + return *std::static_pointer_cast(iterator->second); + } + private: mutable better::shared_mutex mutex_; // Protected by mutex_`.