* Add a key/value pair to a trie. The key is assumed to be \0-terminated. * If there was an existing value for this key, return it. */
| 167 | * If there was an existing value for this key, return it. |
| 168 | */ |
| 169 | static void *add_to_trie(struct trie *root, const char *key, void *value) |
| 170 | { |
| 171 | struct trie *child; |
| 172 | void *old; |
| 173 | int i; |
| 174 | |
| 175 | if (!*key) { |
| 176 | /* we have reached the end of the key */ |
| 177 | old = root->value; |
| 178 | root->value = value; |
| 179 | return old; |
| 180 | } |
| 181 | |
| 182 | for (i = 0; i < root->len; i++) { |
| 183 | if (root->contents[i] == key[i]) |
| 184 | continue; |
| 185 | |
| 186 | /* |
| 187 | * Split this node: child will contain this node's |
| 188 | * existing children. |
| 189 | */ |
| 190 | child = xmalloc(sizeof(*child)); |
| 191 | memcpy(child->children, root->children, sizeof(root->children)); |
| 192 | |
| 193 | child->len = root->len - i - 1; |
| 194 | if (child->len) { |
| 195 | child->contents = xstrndup(root->contents + i + 1, |
| 196 | child->len); |
| 197 | } |
| 198 | child->value = root->value; |
| 199 | root->value = NULL; |
| 200 | root->len = i; |
| 201 | |
| 202 | memset(root->children, 0, sizeof(root->children)); |
| 203 | root->children[(unsigned char)root->contents[i]] = child; |
| 204 | |
| 205 | /* This is the newly-added child. */ |
| 206 | root->children[(unsigned char)key[i]] = |
| 207 | make_trie_node(key + i + 1, value); |
| 208 | return NULL; |
| 209 | } |
| 210 | |
| 211 | /* We have matched the entire compressed section */ |
| 212 | if (key[i]) { |
| 213 | child = root->children[(unsigned char)key[root->len]]; |
| 214 | if (child) { |
| 215 | return add_to_trie(child, key + root->len + 1, value); |
| 216 | } else { |
| 217 | child = make_trie_node(key + root->len + 1, value); |
| 218 | root->children[(unsigned char)key[root->len]] = child; |
| 219 | return NULL; |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | old = root->value; |
| 224 | root->value = value; |
| 225 | return old; |
| 226 | } |
no test coverage detected