Browse Source

Add test case for dereferencing an invalid iterator
- Fixing bug

Sam Jaffe 7 years ago
parent
commit
e2a7b9f7f6
2 changed files with 8 additions and 1 deletions
  1. 4 1
      trie_iterator.hpp
  2. 4 0
      trie_test.cpp

+ 4 - 1
trie_iterator.hpp

@@ -50,7 +50,10 @@ namespace detail {
     trie_iterator_base(Trie * tr) { stk.push(tr); }
     auto operator*() const -> reference { return root(); }
     auto operator->() const -> pointer { return std::addressof(operator*()); }
-    Trie & root() const { return *stk.top(); }
+    Trie & root() const {
+      if (stk.empty()) throw std::runtime_error("Dereferencing invalid iterator");
+      return *stk.top();
+    }
     trie_iterator_base parent() const {
       trie_iterator_base tmp{*this};
       tmp.pop();

+ 4 - 0
trie_test.cpp

@@ -121,6 +121,10 @@ TEST_F(TrieTest, FindMissingPathWillReturnEnd) {
   EXPECT_THAT(data.find({0, 3, 2}), data.end());
 }
 
+TEST_F(TrieTest, DereferenceWithMissingPathThrows) {
+  EXPECT_THROW(*data.find({0, 3, 2}), std::runtime_error);
+}
+
 TEST_F(TrieTest, EraseDropsWholeBranch) {
   EXPECT_THAT(data.find({0, 1}), ::testing::Not(data.end()));
   data.erase(0);