supa_mdx_lint/utils/
char_tree.rs

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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#![allow(dead_code)]
// The [mutable key lint](https://rust-lang.github.io/rust-clippy/master/index.html#mutable_key_type)
// has known false positives when dealing with a struct that has only partial
// interior mutability. In this module, CharNode has a children field that needs
// interior mutability to build the tree, but it's hashed on the value field,
// so the lint can be ignored.
#![allow(clippy::mutable_key_type)]

use std::{
    cell::RefCell,
    collections::HashSet,
    hash::{Hash, Hasher},
    rc::Rc,
};

#[derive(Debug, Eq, PartialEq, Hash)]
enum NodeValue {
    Initial,
    Char(char),
    /// The path leading up to this node is not a valid word and should be
    /// abandoned
    Abort,
    /// The path leading up to this node is a complete word in and of itself
    Finish,
}

#[derive(Debug)]
struct CharNodeInner {
    value: NodeValue,
    children: RefCell<Option<HashSet<CharNode>>>,
}

#[derive(Debug, Clone)]
pub(super) struct CharNode(Rc<CharNodeInner>);

impl PartialEq for CharNode {
    fn eq(&self, other: &Self) -> bool {
        self.0.value == other.0.value
    }
}

impl Eq for CharNode {}

impl Hash for CharNode {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.value.hash(state);
    }
}

impl CharNode {
    pub(super) fn initiate() -> Self {
        Self(Rc::new(CharNodeInner {
            value: NodeValue::Initial,
            children: RefCell::new(None),
        }))
    }

    fn new(value: char) -> Self {
        Self(Rc::new(CharNodeInner {
            value: NodeValue::Char(value),
            children: RefCell::new(None),
        }))
    }

    fn new_abort() -> Self {
        Self(Rc::new(CharNodeInner {
            value: NodeValue::Abort,
            children: RefCell::new(None),
        }))
    }

    fn new_finish() -> Self {
        Self(Rc::new(CharNodeInner {
            value: NodeValue::Finish,
            children: RefCell::new(None),
        }))
    }

    fn add_child(&mut self, child: CharNode) {
        let mut children = self.0.children.borrow_mut();
        let children_set = children.get_or_insert_with(HashSet::new);
        children_set.insert(child);
    }

    pub(super) fn is_root(&self) -> bool {
        self.0.value == NodeValue::Initial
    }

    pub(super) fn append(&mut self, value: char) -> Self {
        let new_child = Self::new(value);
        self.add_child(new_child.clone());
        new_child
    }

    pub(super) fn abort(&mut self) {
        let new_child = Self::new_abort();
        self.add_child(new_child);
    }

    pub(super) fn mark_finished_word(&mut self) {
        let new_child = Self::new_finish();
        self.add_child(new_child);
    }

    pub(super) fn collect(&self) -> Vec<String> {
        fn traverse(node: &CharNode, prefix: &str, result: &mut Vec<String>) {
            match node.0.value {
                NodeValue::Initial => {
                    if let Some(children) = &*node.0.children.borrow() {
                        let new_prefix = "";
                        for child in children {
                            traverse(child, new_prefix, result);
                        }
                    }
                }
                NodeValue::Char(value) => {
                    let new_prefix = format!("{}{}", prefix, value);
                    if let Some(children) = &*node.0.children.borrow() {
                        for child in children {
                            if child.0.value == NodeValue::Finish {
                                result.push(new_prefix.clone());
                            } else {
                                traverse(child, &new_prefix, result);
                            }
                        }
                    } else {
                        result.push(new_prefix);
                    }
                }
                _ => {}
            }
        }

        let mut result = Vec::new();
        traverse(self, "", &mut result);
        result
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_char_tree_collect() {
        let mut root = CharNode::initiate();
        let mut child1 = root.append('a');
        let mut child2 = child1.append('b');
        child1.append('c');
        child2.append('d');

        let collected = child1.collect();
        assert_eq!(collected.len(), 2);
        assert!(collected.contains(&"abd".to_string()));
        assert!(collected.contains(&"ac".to_string()));
    }

    #[test]
    fn test_char_tree_collect_with_aborts() {
        let mut root = CharNode::initiate();
        let mut child1 = root.append('a');
        let mut child2 = child1.append('b');
        child1.append('c');
        child2.append('d');
        let mut aborted_child = child2.append('e');
        aborted_child.abort();

        let collected = child1.collect();
        assert_eq!(collected.len(), 2);
        assert!(collected.contains(&"ac".to_string()));
        assert!(collected.contains(&"abd".to_string()));
    }

    #[test]
    fn test_char_tree_with_mid_path_finish() {
        let mut root = CharNode::initiate();
        let mut child1 = root.append('a');
        let mut child2 = child1.append('b');
        child2.mark_finished_word();
        child2.append('c');

        let collected = child1.collect();
        assert_eq!(collected.len(), 2);
        assert!(collected.contains(&"ab".to_string()));
        assert!(collected.contains(&"abc".to_string()));
    }
}