90 lines
3.1 KiB
C++
90 lines
3.1 KiB
C++
//============================================================================//
|
|
// //
|
|
// artichoke programming language //
|
|
// //
|
|
// Copyright (C) 2025 Erick Saul Guzman Ramos, whoami.artichoke.dev //
|
|
// //
|
|
// //
|
|
// This program is free software: you can redistribute it and/or modify //
|
|
// it under the terms of the GNU Affero General Public License as published //
|
|
// by the Free Software Foundation, either version 3 of the License, or //
|
|
// (at your option) any later version. //
|
|
// //
|
|
// This program is distributed in the hope that it will be useful, //
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
|
|
// GNU Affero General Public License for more details. //
|
|
// //
|
|
// You should have received a copy of the GNU Affero General Public License //
|
|
// along with this program. If not, see <https://www.gnu.org/licenses/>. //
|
|
// //
|
|
//============================================================================//
|
|
|
|
#pragma once
|
|
|
|
#include <map>
|
|
#include <optional>
|
|
#include <string_view>
|
|
|
|
namespace arti::lang {
|
|
|
|
template <typename T>
|
|
struct TrieMap {
|
|
struct Node {
|
|
bool isLeaf;
|
|
std::optional<T> value;
|
|
std::map<char, Node> childs;
|
|
|
|
Node() noexcept
|
|
: isLeaf(false)
|
|
, value(std::nullopt)
|
|
, childs() { }
|
|
|
|
~Node() noexcept = default;
|
|
|
|
Node(Node &&) noexcept = default;
|
|
Node &operator=(Node &&) noexcept = default;
|
|
|
|
Node(const Node &) noexcept = default;
|
|
Node &operator=(const Node &) noexcept = default;
|
|
};
|
|
|
|
Node root;
|
|
|
|
TrieMap() noexcept = default;
|
|
~TrieMap() noexcept = default;
|
|
|
|
TrieMap(TrieMap &&) noexcept = default;
|
|
TrieMap &operator=(TrieMap &&) noexcept = default;
|
|
|
|
TrieMap(const TrieMap &) noexcept = default;
|
|
TrieMap &operator=(const TrieMap &) noexcept = default;
|
|
|
|
void insert(std::string_view str, T &&value) noexcept {
|
|
auto ptrNode = &root;
|
|
|
|
for (auto c : str) {
|
|
ptrNode = &(ptrNode->childs[c]);
|
|
}
|
|
|
|
ptrNode->isLeaf = true;
|
|
ptrNode->value = std::forward<T>(value);
|
|
}
|
|
|
|
T *find(std::string_view str) const noexcept {
|
|
auto ptrNode = &root;
|
|
|
|
for (auto c : str) {
|
|
if (not ptrNode->childs.contains(c)) {
|
|
return nullptr;
|
|
}
|
|
|
|
ptrNode = &(ptrNode->childs.at(c));
|
|
}
|
|
|
|
return ptrNode;
|
|
}
|
|
};
|
|
|
|
} // namespace arti::lang
|