summaryrefslogtreecommitdiffstats
path: root/sqlglotrs/src/trie.rs
blob: 8e6f20ca617568c112e2203ea021d9a6f6600e5a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use std::collections::HashMap;

#[derive(Debug)]
pub struct TrieNode {
    is_word: bool,
    children: HashMap<char, TrieNode>,
}

#[derive(Debug)]
pub enum TrieResult {
    Failed,
    Prefix,
    Exists,
}

impl TrieNode {
    pub fn contains(&self, key: &str) -> (TrieResult, &TrieNode) {
        if key.is_empty() {
            return (TrieResult::Failed, self);
        }

        let mut current = self;
        for c in key.chars() {
            match current.children.get(&c) {
                Some(node) => current = node,
                None => return (TrieResult::Failed, current),
            }
        }

        if current.is_word {
            (TrieResult::Exists, current)
        } else {
            (TrieResult::Prefix, current)
        }
    }
}

#[derive(Debug)]
pub struct Trie {
    pub root: TrieNode,
}

impl Trie {
    pub fn new() -> Self {
        Trie {
            root: TrieNode {
                is_word: false,
                children: HashMap::new(),
            },
        }
    }

    pub fn add<'a, I>(&mut self, keys: I)
    where
        I: Iterator<Item = &'a String>,
    {
        for key in keys {
            let mut current = &mut self.root;
            for c in key.chars() {
                current = current.children.entry(c).or_insert(TrieNode {
                    is_word: false,
                    children: HashMap::new(),
                });
            }
            current.is_word = true;
        }
    }
}