2020-12-26 13:22:44 +03:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2020, the SerenityOS developers.
|
|
|
|
*
|
2021-04-22 11:24:48 +03:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-12-26 13:22:44 +03:00
|
|
|
*/
|
|
|
|
|
2021-04-25 08:53:23 +03:00
|
|
|
#include <LibTest/TestCase.h>
|
2020-12-26 13:22:44 +03:00
|
|
|
|
2021-05-19 17:54:19 +03:00
|
|
|
#include <AK/StringView.h>
|
2020-12-26 13:22:44 +03:00
|
|
|
#include <AK/Trie.h>
|
|
|
|
|
|
|
|
TEST_CASE(normal_behaviour)
|
|
|
|
{
|
|
|
|
Trie<char, String> dictionary('/', "");
|
2021-05-19 17:54:19 +03:00
|
|
|
constexpr StringView data[] { "test", "example", "foo", "foobar" };
|
|
|
|
constexpr size_t total_chars = 18; // root (1), 'test' (4), 'example' (7), 'foo' (3), 'foobar' (3, "foo" already stored).
|
|
|
|
for (auto& view : data) {
|
2020-12-26 13:22:44 +03:00
|
|
|
auto it = view.begin();
|
|
|
|
dictionary.insert(it, view.end(), view, [](auto& parent, auto& it) -> Optional<String> { return String::formatted("{}{}", parent.metadata_value(), *it); });
|
|
|
|
}
|
|
|
|
|
|
|
|
size_t i = 0;
|
|
|
|
for ([[maybe_unused]] auto& node : dictionary)
|
|
|
|
++i;
|
|
|
|
EXPECT_EQ(i, total_chars);
|
|
|
|
|
2021-05-19 17:54:19 +03:00
|
|
|
for (auto& view : data) {
|
2020-12-26 13:22:44 +03:00
|
|
|
auto it = view.begin();
|
|
|
|
auto& node = dictionary.traverse_until_last_accessible_node(it, view.end());
|
|
|
|
EXPECT(it.is_end());
|
|
|
|
EXPECT(node.metadata().has_value());
|
|
|
|
EXPECT_EQ(view, node.metadata_value());
|
|
|
|
}
|
|
|
|
|
2021-05-19 17:54:19 +03:00
|
|
|
constexpr StringView test_data_with_prefix_in_dict[] { "testx", "exampley", "fooa", "foobarb", "fox", "text" };
|
|
|
|
for (auto& view : test_data_with_prefix_in_dict) {
|
2020-12-26 13:22:44 +03:00
|
|
|
auto it = view.begin();
|
|
|
|
auto& node = dictionary.traverse_until_last_accessible_node(it, view.end());
|
|
|
|
EXPECT(!it.is_end());
|
|
|
|
EXPECT(node.metadata().has_value());
|
|
|
|
EXPECT(view.starts_with(node.metadata_value()));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
TEST_CASE(iterate)
|
|
|
|
{
|
|
|
|
Trie<int> bunch_of_numbers { 0 };
|
|
|
|
Array<int, 64> input;
|
|
|
|
for (size_t i = 0; i < input.size(); ++i)
|
|
|
|
input[i] = i;
|
|
|
|
|
2020-12-26 14:13:27 +03:00
|
|
|
bunch_of_numbers.insert(input.begin(), input.end());
|
|
|
|
|
2020-12-26 13:22:44 +03:00
|
|
|
// Iteration order is preorder (order between adjacent nodes is not defined, but parents come before children)
|
|
|
|
// in this case, the tree is linear.
|
|
|
|
size_t i = 0;
|
2020-12-26 14:13:27 +03:00
|
|
|
bool is_root = true;
|
2020-12-26 13:22:44 +03:00
|
|
|
for (auto& node : bunch_of_numbers) {
|
2020-12-26 14:13:27 +03:00
|
|
|
if (is_root) {
|
|
|
|
is_root = false;
|
|
|
|
continue;
|
|
|
|
}
|
2020-12-26 13:22:44 +03:00
|
|
|
EXPECT_EQ(input[i], node.value());
|
|
|
|
++i;
|
|
|
|
}
|
|
|
|
}
|