diff --git a/ntcore/src/main/native/cpp/LocalStorage.cpp b/ntcore/src/main/native/cpp/LocalStorage.cpp index 01cd8f2e6c..0ca15bbcb5 100644 --- a/ntcore/src/main/native/cpp/LocalStorage.cpp +++ b/ntcore/src/main/native/cpp/LocalStorage.cpp @@ -83,6 +83,7 @@ struct TopicData { unsigned int flags{0}; // for NT3 APIs std::string propertiesStr{"{}"}; // cached string for GetTopicInfo() et al wpi::json properties = wpi::json::object(); + NT_Entry entry{0}; // cached entry for GetEntry() bool onNetwork{false}; // true if there are any remote publishers @@ -2331,11 +2332,15 @@ NT_Entry LocalStorage::GetEntry(std::string_view name) { // Get the topic data auto* topic = m_impl->GetOrCreateTopic(name); - // Create subscriber - auto* subscriber = m_impl->AddLocalSubscriber(topic, {}); + if (topic->entry == 0) { + // Create subscriber + auto* subscriber = m_impl->AddLocalSubscriber(topic, {}); - // Create entry - return m_impl->AddEntry(subscriber)->handle; + // Create entry + topic->entry = m_impl->AddEntry(subscriber)->handle; + } + + return topic->entry; } std::string LocalStorage::GetEntryName(NT_Handle subentryHandle) { diff --git a/ntcore/src/test/native/cpp/LocalStorageTest.cpp b/ntcore/src/test/native/cpp/LocalStorageTest.cpp index aca3041278..96a0ee76c4 100644 --- a/ntcore/src/test/native/cpp/LocalStorageTest.cpp +++ b/ntcore/src/test/native/cpp/LocalStorageTest.cpp @@ -63,6 +63,14 @@ TEST_F(LocalStorageTest, GetEntryEmptyName) { EXPECT_EQ(storage.GetEntry(""), 0u); } +TEST_F(LocalStorageTest, GetEntryCached) { + EXPECT_CALL(network, Subscribe(_, wpi::SpanEq({std::string{"tocache"}}), + IsPubSubOptions({}))); + + auto entry1 = storage.GetEntry("tocache"); + EXPECT_EQ(entry1, storage.GetEntry("tocache")); +} + TEST_F(LocalStorageTest, GetTopicName) { EXPECT_EQ(storage.GetTopicName(fooTopic), "foo"); EXPECT_EQ(storage.GetTopicName(barTopic), "bar");