Skip to content

Commit

Permalink
singleton manager: overload getTyped with non-constructing version (e…
Browse files Browse the repository at this point in the history
…nvoyproxy#18362)

Signed-off-by: Jose Nino <[email protected]>
  • Loading branch information
junr03 authored Oct 1, 2021
1 parent 34edbca commit 3941b63
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
9 changes: 9 additions & 0 deletions envoy/singleton/manager.h
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,15 @@ class Manager {
return std::dynamic_pointer_cast<T>(get(name, cb));
}

/**
* This is a non-constructing getter. Use when the caller can deal with instances where
* the singleton being accessed may not have been constructed previously.
* @return InstancePtr the singleton. nullptr if the singleton does not exist.
*/
template <class T> std::shared_ptr<T> getTyped(const std::string& name) {
return std::dynamic_pointer_cast<T>(get(name, [] { return nullptr; }));
}

/**
* Get a singleton and create it if it does not exist.
* @param name supplies the singleton name. Must be registered via RegistrationImpl.
Expand Down
17 changes: 17 additions & 0 deletions test/common/singleton/manager_impl_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,23 @@ TEST(SingletonManagerImplTest, Basic) {
singleton.reset();
}

TEST(SingletonManagerImplTest, NonConstructingGetTyped) {
ManagerImpl manager(Thread::threadFactoryForTest());

// Access without first constructing should be null.
EXPECT_EQ(nullptr, manager.getTyped<TestSingleton>("test_singleton"));

std::shared_ptr<TestSingleton> singleton = std::make_shared<TestSingleton>();
// Use a construct on first use getter.
EXPECT_EQ(singleton, manager.get("test_singleton", [singleton] { return singleton; }));
// Now access should return the constructed singleton.
EXPECT_EQ(singleton, manager.getTyped<TestSingleton>("test_singleton"));
EXPECT_EQ(1UL, singleton.use_count());

EXPECT_CALL(*singleton, onDestroy());
singleton.reset();
}

} // namespace
} // namespace Singleton
} // namespace Envoy

0 comments on commit 3941b63

Please sign in to comment.