From 05cb45ca14469f92f07c11f35a599ac6f87539fa Mon Sep 17 00:00:00 2001 From: Stephen Seo Date: Tue, 3 Sep 2019 15:15:09 +0900 Subject: [PATCH] Prevent exceptions being thrown in TSQueue TSQueue's top() and top_and_pop() now return std::optional instead of just T. --- cpp_impl/src/TSQueue.hpp | 21 ++++++++++++++------- cpp_impl/src/UDPConnection.cpp | 4 ++-- cpp_impl/src/test/TestTSQueue.cpp | 2 +- 3 files changed, 17 insertions(+), 10 deletions(-) diff --git a/cpp_impl/src/TSQueue.hpp b/cpp_impl/src/TSQueue.hpp index 1985eee..81dadf5 100644 --- a/cpp_impl/src/TSQueue.hpp +++ b/cpp_impl/src/TSQueue.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include @@ -23,9 +24,9 @@ class TSQueue { TSQueue &operator=(TSQueue &&other); bool push(const T &data); - T top(); + std::optional top(); bool pop(); - T top_and_pop(); + std::optional top_and_pop(); void clear(); void changeCapacity(unsigned int newCapacity); unsigned int size(); @@ -81,9 +82,12 @@ bool TSQueue::push(const T &data) { } template -T TSQueue::top() { +std::optional TSQueue::top() { std::lock_guard lock(mutex); - T value = rb.top(); + std::optional value = std::nullopt; + if(!rb.empty()) { + value = rb.top(); + } return value; } @@ -98,10 +102,13 @@ bool TSQueue::pop() { } template -T TSQueue::top_and_pop() { +std::optional TSQueue::top_and_pop() { std::lock_guard lock(mutex); - T value = rb.top(); - rb.pop(); + std::optional value = std::nullopt; + if(!rb.empty()) { + value = rb.top(); + rb.pop(); + } return value; } diff --git a/cpp_impl/src/UDPConnection.cpp b/cpp_impl/src/UDPConnection.cpp index 7292a02..4b924bd 100644 --- a/cpp_impl/src/UDPConnection.cpp +++ b/cpp_impl/src/UDPConnection.cpp @@ -496,11 +496,11 @@ void UDPC_update(UDPC_HContext ctx) { bool isResending = false; if(!iter->second.priorityPkts.empty()) { // TODO verify getting struct copy is valid - pInfo = iter->second.priorityPkts.top(); + pInfo = std::move(iter->second.priorityPkts.top().value()); iter->second.priorityPkts.pop(); isResending = true; } else { - pInfo = iter->second.sendPkts.top(); + pInfo = std::move(iter->second.sendPkts.top().value()); iter->second.sendPkts.pop(); } std::unique_ptr buf = std::make_unique(20 + pInfo.dataSize); diff --git a/cpp_impl/src/test/TestTSQueue.cpp b/cpp_impl/src/test/TestTSQueue.cpp index 58e2a7d..fc6dc20 100644 --- a/cpp_impl/src/test/TestTSQueue.cpp +++ b/cpp_impl/src/test/TestTSQueue.cpp @@ -133,7 +133,7 @@ TEST(TSQueue, Concurrent) int top; for(int i = 0; i < 4; ++i) { - top = q.top(); + top = q.top().value(); EXPECT_TRUE(q.pop()); EXPECT_EQ(q.size(), 3 - i); printf("%d ", top);