trie.cpp (1173B)
1 #include "poafloc.hpp" 2 3 #include <cstdint> 4 5 namespace poafloc { 6 7 Parser::trie_t::~trie_t() noexcept { 8 for (uint8_t i = 0; i < 26; i++) { 9 delete children[i]; 10 } 11 } 12 13 bool Parser::trie_t::insert(const char *option, int key) { 14 trie_t *crnt = this; 15 16 if (!is_valid(option)) return false; 17 for (; *option; option++) { 18 if (!crnt->terminal) crnt->key = key; 19 crnt->count++; 20 21 const uint8_t idx = *option - 'a'; 22 if (!crnt->children[idx]) crnt->children[idx] = new trie_t(); 23 crnt = crnt->children[idx]; 24 } 25 26 crnt->terminal = true; 27 crnt->key = key; 28 29 return true; 30 } 31 32 int Parser::trie_t::get(const char *option) const { 33 const trie_t *crnt = this; 34 35 if (!is_valid(option)) return 0; 36 for (; *option; option++) { 37 const uint8_t idx = *option - 'a'; 38 if (!crnt->children[idx]) return 0; 39 crnt = crnt->children[idx]; 40 } 41 42 if (!crnt->terminal && crnt->count > 1) return 0; 43 return crnt->key; 44 } 45 46 bool Parser::trie_t::is_valid(const char *option) { 47 for (; *option; option++) { 48 if (!std::islower(*option)) return false; 49 } 50 return true; 51 } 52 53 } // namespace args