Add field 'committed' to obj_pool.h
[svn-fe.git] / string_pool.c
blob636dcbe84751726b951d04650acf699f91e3e237
1 /*
2 * Licensed under a two-clause BSD-style license.
3 * See LICENSE for details.
4 */
6 #include <string.h>
7 #include <stdint.h>
9 #include "trp.h"
10 #include "obj_pool.h"
11 #include "string_pool.h"
13 typedef struct node_s node_t;
14 static struct trp_root tree = { ~0 };
16 struct node_s {
17 uint32_t offset;
18 struct trp_node children;
21 /* Create two memory pools: one for node_t, and another for strings */
22 obj_pool_gen(node, node_t, 4096);
23 obj_pool_gen(string, char, 4096);
25 static char *node_value(node_t *node)
27 return node ? string_pointer(node->offset) : NULL;
30 static int node_cmp(node_t *a, node_t *b)
32 return strcmp(node_value(a), node_value(b));
35 /* Build a Treap from the node_s structure (a trp_node w/ offset) */
36 trp_gen(static, tree_, node_t, children, node, node_cmp);
38 char *pool_fetch(uint32_t entry)
40 return node_value(node_pointer(entry));
43 uint32_t pool_intern(char *key)
45 /* Canonicalize key */
46 node_t *match = NULL;
47 uint32_t key_len;
48 if (key == NULL)
49 return ~0;
50 key_len = strlen(key) + 1;
51 node_t *node = node_pointer(node_alloc(1));
52 node->offset = string_alloc(key_len);
53 strcpy(node_value(node), key);
54 match = tree_search(&tree, node);
55 if (!match) {
56 tree_insert(&tree, node);
57 } else {
58 node_free(1);
59 string_free(key_len);
60 node = match;
62 return node_offset(node);
65 uint32_t pool_tok_r(char *str, const char *delim, char **saveptr)
67 char *token = strtok_r(str, delim, saveptr);
68 return token ? pool_intern(token) : ~0;
71 void pool_print_seq(uint32_t len, uint32_t *seq, char delim, FILE *stream)
73 uint32_t i;
74 for (i = 0; i < len && ~seq[i]; i++) {
75 fputs(pool_fetch(seq[i]), stream);
76 if (i < len - 1 && ~seq[i + 1])
77 fputc(delim, stream);
81 uint32_t pool_tok_seq(uint32_t max, uint32_t *seq, char *delim, char *str)
83 char *context = NULL;
84 uint32_t length = 0, token = str ? pool_tok_r(str, delim, &context) : ~0;
85 while (length < max) {
86 seq[length++] = token;
87 if (token == ~0)
88 break;
89 token = pool_tok_r(NULL, delim, &context);
91 seq[length ? length - 1 : 0] = ~0;
92 return length;
95 void pool_init(void)
97 uint32_t node;
98 node_init();
99 string_init();
100 for (node = 0; node < node_pool.size; node++) {
101 tree_insert(&tree, node_pointer(node));
105 void pool_reset(void)
107 node_reset();
108 string_reset();