Commit 34a5bd8c authored by Rui Zhang's avatar Rui Zhang Committed by Facebook Github Bot

Add Singleton::apply and unit tests.

Summary: Adds a callback interface to facilitate adding elision support for folly::Singleton. Planned to add context-aware elision support which will use an adaptation method based on the interface's callsite information (ie, the type of the Singleton instance, T, and the type of the callback function, F).

Reviewed By: nbronson

Differential Revision: D15970597

fbshipit-source-id: 1010322c64d1b7900b4bef5b35059238efabb071
parent 10e490c1
......@@ -142,6 +142,12 @@ folly::ReadMostlySharedPtr<T> SingletonHolder<T>::try_get_fast() {
return instance_weak_fast_.lock();
}
template <typename T>
template <typename Func>
invoke_result_t<Func, T*> detail::SingletonHolder<T>::apply(Func f) {
return f(try_get().get());
}
template <typename T>
void SingletonHolder<T>::vivify() {
if (UNLIKELY(
......
......@@ -313,6 +313,8 @@ struct SingletonHolder : public SingletonHolderBase {
inline std::weak_ptr<T> get_weak();
inline std::shared_ptr<T> try_get();
inline folly::ReadMostlySharedPtr<T> try_get_fast();
template <typename Func>
inline invoke_result_t<Func, T*> apply(Func f);
inline void vivify();
void registerSingleton(CreateFunc c, TeardownFunc t);
......@@ -599,6 +601,22 @@ class Singleton {
return getEntry().try_get_fast();
}
/**
* Applies a callback to the possibly-nullptr singleton instance, returning
* the callback's result. That is, the following two are functionally
* equivalent:
* singleton.apply(std::ref(f));
* f(singleton.try_get().get());
*
* For example, the following returns the singleton
* instance directly without any extra operations on the instance:
* auto ret = Singleton<T>::apply([](auto* v) { return v; });
*/
template <typename Func>
static invoke_result_t<Func, T*> apply(Func f) {
return getEntry().apply(std::ref(f));
}
// Quickly ensure the instance exists.
static void vivify() {
getEntry().vivify();
......
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment