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
use crate::collections::HashMap;
use crate::{Component, ComponentRef, IntoComponent};
use std::mem;
#[derive(Debug, Clone)]
pub struct Names<T> {
root: Node<T>,
}
impl<T> Default for Names<T> {
fn default() -> Self {
Names {
root: Default::default(),
}
}
}
impl<T> Names<T> {
pub fn new() -> Self {
Self::default()
}
pub fn insert<I>(&mut self, iter: I, value: T) -> Option<T>
where
I: IntoIterator,
I::Item: IntoComponent,
{
let mut current = &mut self.root;
for c in iter {
current = current.children.entry(c.into_component()).or_default();
}
mem::replace(&mut current.term, Some(value))
}
pub fn contains<I>(&self, iter: I) -> bool
where
I: IntoIterator,
I::Item: IntoComponent,
{
self.find_node(iter)
.map(|n| n.term.is_some())
.unwrap_or_default()
}
pub fn get<I>(&self, iter: I) -> Option<&T>
where
I: IntoIterator,
I::Item: IntoComponent,
{
self.find_node(iter).and_then(|n| n.term.as_ref())
}
pub fn contains_prefix<I>(&self, iter: I) -> bool
where
I: IntoIterator,
I::Item: IntoComponent,
{
self.find_node(iter).is_some()
}
pub fn iter_components<'a, I: 'a>(
&'a self,
iter: I,
) -> impl Iterator<Item = ComponentRef<'a>> + 'a
where
I: IntoIterator,
I::Item: IntoComponent,
{
let mut current = &self.root;
for c in iter {
let c = c.into_component();
current = match current.children.get(&c) {
Some(node) => node,
None => return IterComponents(None),
};
}
return IterComponents(Some(current.children.keys()));
struct IterComponents<I>(Option<I>);
impl<'a, I> Iterator for IterComponents<I>
where
I: Iterator<Item = &'a Component>,
{
type Item = ComponentRef<'a>;
fn next(&mut self) -> Option<Self::Item> {
let mut iter = self.0.take()?;
let next = iter.next()?;
self.0 = Some(iter);
Some(next.as_component_ref())
}
}
}
fn find_node<I>(&self, iter: I) -> Option<&Node<T>>
where
I: IntoIterator,
I::Item: IntoComponent,
{
let mut current = &self.root;
for c in iter {
let c = c.as_component_ref().into_component();
current = current.children.get(&c)?;
}
Some(current)
}
}
#[derive(Debug, Clone)]
struct Node<T> {
term: Option<T>,
children: HashMap<Component, Node<T>>,
}
impl<T> Default for Node<T> {
fn default() -> Self {
Self {
term: Default::default(),
children: Default::default(),
}
}
}