diff --git a/src/utils/path_trie.cpp b/src/utils/path_trie.cpp index e7954e5..a8443ca 100644 --- a/src/utils/path_trie.cpp +++ b/src/utils/path_trie.cpp @@ -16,8 +16,9 @@ PathTrie::PathTrie(const PathTrie& other) : root_(nullptr) { if (other.root_) { - root_ = new Node(*other.root_); CopyNode(root_, other.root_); + } else { + root_ = new Node(); } } @@ -27,11 +28,11 @@ PathTrie& PathTrie::operator=(const PathTrie& other) return *this; DeleteNode(root_); + root_ = nullptr; if (other.root_) { - root_ = new Node(*other.root_); CopyNode(root_, other.root_); } else { - root_ = nullptr; + root_ = new Node(); } return *this; @@ -156,6 +157,9 @@ PathTrie::~PathTrie() void PathTrie::DeleteNode(Node* node) { #ifndef LUA_OAS_VALIDATOR // LUA manages garbage collection itself + if (!node) { + return; + } for (auto& pair : node->children) { DeleteNode(pair.second); } diff --git a/test/unittest/src/utils/path_trie.cpp b/test/unittest/src/utils/path_trie.cpp index f63c7b7..6e1436c 100644 --- a/test/unittest/src/utils/path_trie.cpp +++ b/test/unittest/src/utils/path_trie.cpp @@ -65,3 +65,32 @@ TEST_F(PathTrieTest, InsertAndSearchMultiParamPath) EXPECT_EQ(std::string(param_idxs[3].beg, param_idxs[3].end), "123"); EXPECT_EQ(std::string(param_idxs[5].beg, param_idxs[5].end), "update"); } + +// Verify copy constructor correctly duplicates the trie +TEST_F(PathTrieTest, CopyConstructor) +{ + trie_.Insert("/api/data/{id}"); + PathTrie copied(trie_); + std::string oas_path; + std::unordered_map param_idxs; + std::string search_path = "/api/data/456"; + EXPECT_TRUE(copied.Search(search_path.data(), search_path.data() + search_path.size(), oas_path, param_idxs)); + EXPECT_EQ(oas_path, "/api/data/{id}"); + ASSERT_TRUE(param_idxs.find(3) != param_idxs.end()); + EXPECT_EQ(std::string(param_idxs[3].beg, param_idxs[3].end), "456"); +} + +// Verify copy assignment correctly duplicates the trie +TEST_F(PathTrieTest, CopyAssignment) +{ + PathTrie other; + other.Insert("/api/info/{name}"); + trie_ = other; + std::string oas_path; + std::unordered_map param_idxs; + std::string search_path = "/api/info/john"; + EXPECT_TRUE(trie_.Search(search_path.data(), search_path.data() + search_path.size(), oas_path, param_idxs)); + EXPECT_EQ(oas_path, "/api/info/{name}"); + ASSERT_TRUE(param_idxs.find(2) != param_idxs.end()); + EXPECT_EQ(std::string(param_idxs[2].beg, param_idxs[2].end), "john"); +}